Challenge - 5 Problems
Master of new operator
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of dynamic array allocation
What is the output of this C++ code snippet?
C++
#include <iostream> int main() { int* arr = new int[3]{1, 2, 3}; std::cout << arr[1] << std::endl; delete[] arr; return 0; }
Attempts:
2 left
💡 Hint
Remember that array indexing starts at 0.
✗ Incorrect
The array is initialized with values {1, 2, 3}. arr[1] accesses the second element, which is 2.
❓ Predict Output
intermediate2:00remaining
Output of new operator with class object
What will this program print?
C++
#include <iostream> class Box { public: int length; Box(int l) : length(l) {} }; int main() { Box* b = new Box(10); std::cout << b->length << std::endl; delete b; return 0; }
Attempts:
2 left
💡 Hint
Check how the constructor initializes the length.
✗ Incorrect
The Box object is created with length 10, so printing b->length outputs 10.
❓ Predict Output
advanced2:00remaining
Output when forgetting to delete dynamic memory
What is the output of this program?
C++
#include <iostream> int main() { int* p = new int(5); *p = 10; std::cout << *p << std::endl; // no delete called return 0; }
Attempts:
2 left
💡 Hint
The program prints the value pointed by p before exiting.
✗ Incorrect
The pointer p points to an int initialized to 5, then changed to 10. The program prints 10. Not deleting causes a memory leak but no immediate runtime error.
❓ Predict Output
advanced2:00remaining
Output of new operator with placement new
What will this program output?
C++
#include <iostream> #include <new> int main() { char buffer[sizeof(int)]; int* p = new(buffer) int(42); std::cout << *p << std::endl; p->~int(); return 0; }
Attempts:
2 left
💡 Hint
Placement new constructs an object in pre-allocated memory.
✗ Incorrect
Placement new constructs an int with value 42 in buffer. Printing *p outputs 42.
🧠 Conceptual
expert2:00remaining
What error occurs when deleting non-dynamically allocated memory?
Consider this code snippet:
int x = 5;
int* p = &x;
delete p;
What happens when this code runs?
Attempts:
2 left
💡 Hint
delete should only be used on memory allocated with new.
✗ Incorrect
Deleting a pointer to a stack variable causes undefined behavior and often runtime errors.