Challenge - 5 Problems
Delete Operator Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of deleting a dynamically allocated int
What is the output of this C++ code snippet?
C++
#include <iostream> int main() { int* p = new int(10); std::cout << *p << std::endl; delete p; // std::cout << *p << std::endl; // Uncommenting this causes undefined behavior std::cout << "Deleted" << std::endl; return 0; }
Attempts:
2 left
💡 Hint
Remember that deleting a pointer frees memory but does not print anything by itself.
✗ Incorrect
The program prints the value pointed by p (10), then deletes the memory, and finally prints "Deleted". The delete operator does not produce output.
❓ Predict Output
intermediate2:00remaining
Effect of deleting an array allocated with new[]
What is the output of this C++ code?
C++
#include <iostream> int main() { int* arr = new int[3]{1, 2, 3}; delete arr; std::cout << arr[0] << std::endl; return 0; }
Attempts:
2 left
💡 Hint
Deleting an array allocated with new[] requires a special delete syntax.
✗ Incorrect
Using delete instead of delete[] on an array causes undefined behavior. Accessing arr[0] after delete is also undefined.
❓ Predict Output
advanced2:00remaining
Output when deleting a nullptr pointer
What happens when you delete a nullptr pointer in C++?
C++
#include <iostream> int main() { int* p = nullptr; delete p; std::cout << "Deleted nullptr" << std::endl; return 0; }
Attempts:
2 left
💡 Hint
Deleting nullptr is safe and does nothing.
✗ Incorrect
The delete operator does nothing when given a nullptr pointer. The program prints "Deleted nullptr".
❓ Predict Output
advanced2:00remaining
Output of deleting a pointer twice
What is the output or behavior of this code?
C++
#include <iostream> int main() { int* p = new int(5); 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 and usually a runtime error like a crash.
🧠 Conceptual
expert3:00remaining
Which delete operator call is correct for this class?
Given the class below, which delete statement correctly frees the allocated memory without causing undefined behavior?
C++
class MyClass { public: int* data; MyClass() { data = new int[5]; } ~MyClass() { delete[] data; } }; int main() { MyClass* obj = new MyClass(); // Which delete is correct here? // A) delete obj->data; // B) delete[] obj->data; // C) delete[] obj; // D) delete obj; return 0; }
Attempts:
2 left
💡 Hint
Deleting the object calls its destructor which deletes the array properly.
✗ Incorrect
The correct way is to delete the object pointer (delete obj;). This calls the destructor which deletes the array with delete[]. Deleting obj->data directly is unsafe here because the destructor also deletes it, causing double delete.