Pointers and Memory Management
Dynamic Memory Allocation
new and delete operators — heap allocation in C++
Interview: Core C++ memory management — new/delete, double-free, dangling pointers, and why smart pointers exist
Dynamic Memory Allocation
Dynamic memory allocation allows creating objects whose lifetime and size are determined at runtime, on the heap (also called the free store). Unlike stack objects (automatically destroyed when scope ends), heap objects persist until explicitly deallocated with delete.
new vs malloc
new is type-aware: it allocates memory AND calls the constructor. malloc only allocates raw bytes — no construction. Similarly, delete calls the destructor before freeing memory; free just releases bytes. In C++, always use new/delete over malloc/free — and prefer smart pointers over both.
Common Memory Errors
Memory Leak
Allocated memory never freed. The program gradually consumes all available memory.
Double Free
Calling delete on an already-deleted pointer. Corrupts the heap allocator — undefined behavior.
Dangling Pointer
Using a pointer after the memory it pointed to was deleted. Reads garbage or corrupts memory.
Mismatch
Using delete on array memory (should be delete[]) or mixing malloc/delete. Always match allocator.
Placement new
Placement new constructs an object in pre-allocated memory without allocating: new (ptr) Type(args). Used in memory pools, custom allocators, and embedded systems where allocation overhead must be avoided. The destructor must be called manually: ptr->~Type();
Interview Corner
Q: What happens if new fails to allocate memory?
A: By default, new throws std::bad_alloc. The nothrow version new (std::nothrow) T returns nullptr instead. In embedded/critical systems, a custom new_handler can be installed via std::set_new_handler() to log, release cached memory, or terminate gracefully.
Q: What is the difference between delete and delete[]?
A: delete destroys a single object allocated with new. delete[] destroys an entire array allocated with new[], calling the destructor for each element. Using delete on array memory is undefined behavior — it calls only the first element's destructor and the allocator may corrupt the heap. Always match: new delete, new[] delete[].
Common Pitfalls
- Exception safety: If an exception is thrown between
newand the correspondingdelete, the memory leaks. Use RAII (smart pointers) to ensure cleanup even with exceptions. - Mismatching new[] with delete: Always use
delete[]for array allocations — undefined behavior otherwise.
Best Practices
- Never use raw
new/deletein new code. Usestd::make_uniqueandstd::make_shared. - Set pointers to
nullptrafter delete to prevent dangling pointer use:delete p; p = nullptr;