0
0
C++programming~20 mins

delete operator in C++ - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Delete Operator Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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;
}
A
Runtime error
B
Deleted
10
C
10
Deleted
D
Compilation error
Attempts:
2 left
💡 Hint
Remember that deleting a pointer frees memory but does not print anything by itself.
Predict Output
intermediate
2: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;
}
A
Runtime error or undefined behavior
B
Compilation error
C
1
D
0
Attempts:
2 left
💡 Hint
Deleting an array allocated with new[] requires a special delete syntax.
Predict Output
advanced
2: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;
}
A
Compilation error
B
Runtime error
C
No output
D
Deleted nullptr
Attempts:
2 left
💡 Hint
Deleting nullptr is safe and does nothing.
Predict Output
advanced
2: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;
}
A
Runtime error (double free)
B
Done
C
Compilation error
D
Undefined output
Attempts:
2 left
💡 Hint
Deleting the same pointer twice causes a runtime error.
🧠 Conceptual
expert
3: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;
}
Adelete[] obj->data;
Bdelete obj;
Cdelete[] obj;
Ddelete obj->data;
Attempts:
2 left
💡 Hint
Deleting the object calls its destructor which deletes the array properly.