Challenge - 5 Problems
Memory Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of dynamic memory allocation with pointers
What is the output of the following C++ code?
C++
#include <iostream> int main() { int* p = new int(10); std::cout << *p << std::endl; delete p; return 0; }
Attempts:
2 left
💡 Hint
Remember that new allocates memory and initializes the value.
✗ Incorrect
The pointer p points to a dynamically allocated int initialized to 10. Dereferencing *p prints 10.
❓ Predict Output
intermediate2:00remaining
Output after deleting and accessing pointer
What happens when you run this C++ code?
C++
#include <iostream> int main() { int* p = new int(5); delete p; std::cout << *p << std::endl; return 0; }
Attempts:
2 left
💡 Hint
Accessing memory after delete is unsafe.
✗ Incorrect
After delete, the pointer p is dangling. Dereferencing it causes undefined behavior, which may print garbage or crash.
🧠 Conceptual
advanced2:00remaining
Correct use of delete[] for arrays
Which option correctly deallocates the dynamically allocated array in C++?
Attempts:
2 left
💡 Hint
Arrays allocated with new[] must be deallocated with delete[].
✗ Incorrect
Using delete[] properly frees the entire array. Using delete without [] causes undefined behavior. free() is for malloc, not new.
❓ Predict Output
advanced2:00remaining
Output of double delete error
What error or output occurs when running this code?
C++
#include <iostream> int main() { int* p = new int(7); delete p; delete p; std::cout << "Done" << std::endl; return 0; }
Attempts:
2 left
💡 Hint
Deleting the same pointer twice causes a runtime error.
✗ Incorrect
Double deleting a pointer causes undefined behavior, often a runtime error like double free or corruption.
🧠 Conceptual
expert3:00remaining
Memory leak detection in C++ code
Which option describes the memory leak in the following code snippet?
C++
void foo() { int* p = new int[10]; p = new int[20]; delete[] p; }
Attempts:
2 left
💡 Hint
Reassigning pointer without deleting old memory causes leak.
✗ Incorrect
The first allocated array is overwritten by p = new int[20]; without deleting it first, causing a memory leak.