C++ Memory Management Practice (Interactive)
C++ — Memory Management Practice
15 auto-graded MCQ questions covering stack vs heap allocation, pointers, references, smart pointers, RAII, memory leaks, new/delete, sizeof, and alignment. Select an answer, submit, and review the explanation.
Stack vs Heap
Pointers and References
new and delete
Smart Pointers
RAII
sizeof and Alignment
Memory Leaks
Common Mistakes
Mixing new[] with delete (or new with delete[]): Using delete on memory allocated with new[] (or vice versa) is undefined behaviour. The runtime may call the wrong number of destructors and corrupt heap metadata. Always match allocation form with deallocation form, or better yet, use std::vector or std::array instead of raw new[].
Returning a reference to a local variable: A function that returns int& to a stack-local variable creates a dangling reference — the local is destroyed when the function returns, and the reference points to invalid memory. This is undefined behaviour that may appear to work in debug builds but crash in release. Return by value or use heap allocation with smart pointers.
Forgetting that shared_ptr copies share the same control block: Two shared_ptr instances pointing to the same object share a reference count. Resetting one does not free the object if the other still exists. This is correct behaviour but can be confusing — if you need exclusive ownership, use unique_ptr instead.
Cross-References
- Site Home: Main landing page for Programming notes.
- Types: Type system fundamentals.
- Resource Management: RAII and smart pointers.
- Templates: Generic programming and metaprogramming.