C++

Memory Management

12 question(s)

What is the difference between the stack and the heap?

Beginner
The stack is a region of memory for automatic (local) variables, managed by the compiler with LIFO allocation and fast, deterministic lifetime tied to scope. The heap (free store) is for dynamic allocation via new/malloc, managed manually (or by smart pointers), with flexible lifetime but slower allocation and risk of leaks.
void f() {
    int a = 10;          // stack
    int* p = new int(20); // heap
    delete p;            // must free heap memory
}
Real-world example Local loop counters live on the stack; a dynamically sized buffer is allocated on the heap.

Common follow-ups: Which is faster to allocate? | Who frees heap memory?

RAII & Smart Pointers References & Pointers Memory Management

What do new and delete do?

Beginner
new allocates memory on the heap and constructs an object, returning a pointer; delete calls the destructor and frees the memory. For arrays use new[] and delete[]. Every new must be matched by exactly one delete (and new[] with delete[]) or you get leaks or undefined behavior.
int* p  = new int(5);      delete p;
int* a  = new int[10];     delete[] a;
Real-world example A container implementation uses new[]/delete[] to manage its underlying buffer.

Common follow-ups: What happens if you mismatch new[] with delete? | Why prefer smart pointers?

RAII & Smart Pointers Memory Management Memory Management

What is a memory leak?

Beginner
A memory leak occurs when heap memory is allocated but never freed, so it remains reserved for the program's lifetime, gradually exhausting available memory. Leaks happen when a delete is missed, a pointer is overwritten before freeing, or an exception skips the cleanup. RAII/smart pointers prevent most leaks.
int* p = new int(1);
p = new int(2);   // first allocation leaked
Real-world example A long-running server slowly consumes all memory because a handler forgets to free per-request buffers.

Common follow-ups: How do smart pointers prevent leaks? | What tools detect leaks?

RAII & Smart Pointers Memory Management Memory Management

What is a dangling pointer and how does it arise?

Intermediate
A dangling pointer points to memory that has been freed or gone out of scope, so dereferencing it is undefined behavior. It arises from using a pointer after delete, returning the address of a local variable, or holding a pointer/iterator into a container after it reallocates. Setting freed pointers to nullptr and using smart pointers reduces the risk.
int* p = new int(5);
delete p;
*p = 10;   // dangling: undefined behavior
Real-world example A cached raw pointer crashes the app after the object it referenced was destroyed.

Common follow-ups: How do you avoid dangling pointers? | What is use-after-free?

References & Pointers RAII & Smart Pointers Memory Management

What is the difference between malloc/free and new/delete?

Intermediate
malloc/free are C library functions that only allocate/free raw memory and don't call constructors or destructors; new/delete are C++ operators that also construct and destruct objects and are type-safe (no cast needed). In C++ you should use new/delete (or better, smart pointers), not malloc, for objects with non-trivial lifetimes.
MyClass* a = (MyClass*)malloc(sizeof(MyClass)); // no ctor called
MyClass* b = new MyClass();                     // ctor called
Real-world example Mixing malloc with a C++ class skips its constructor, leaving members uninitialized and crashing later.

Common follow-ups: Why is new type-safe? | Can you mix malloc with delete?

RAII & Smart Pointers Memory Management Memory Management

What is placement new?

Intermediate
Placement new constructs an object at a pre-allocated memory address rather than allocating new memory. It's used to separate allocation from construction (e.g., in custom allocators, memory pools, or containers). You must manually call the destructor for placement-new objects; you don't delete them.
alignas(MyClass) char buf[sizeof(MyClass)];
MyClass* p = new (buf) MyClass();  // construct in buf
p->~MyClass();                     // explicit destruction
Real-world example A memory pool uses placement new to construct objects in a pre-allocated block, avoiding per-object heap calls.

Common follow-ups: How do you destroy a placement-new object? | Where is placement new used?

RAII & Smart Pointers STL Memory Management

What is the difference between shallow copy and deep copy in memory terms?

Advanced
A shallow copy copies pointer values, so two objects share the same heap memory—leading to double-free or dangling issues when one is destroyed. A deep copy allocates new memory and copies the pointed-to data, giving each object independent ownership. The Rule of Three/Five ensures correct copy/move semantics for classes managing resources.
// Deep copy in copy constructor
MyClass(const MyClass& o) : data(new int[o.n]), n(o.n) {
    std::copy(o.data, o.data + n, data);
}
Real-world example A class that shallow-copies a buffer double-frees it, crashing when both copies are destroyed.

Common follow-ups: What is the Rule of Three/Five? | Why does shallow copy cause double-free?

Move Semantics OOP & Classes Memory Management

What is memory alignment and why does it matter?

Advanced
Alignment is the requirement that objects be placed at memory addresses that are multiples of their alignment (often their size), so the CPU can access them efficiently (or at all, on some architectures). alignof queries it and alignas sets it. Misalignment can cause performance penalties or hardware faults; it also affects struct padding and layout.
struct S { char c; int i; };  // padding inserted for i's alignment
static_assert(alignof(int) == 4);
Real-world example A struct is reordered and padded so each member meets its alignment, changing sizeof.

Common follow-ups: What is struct padding? | How do alignas/alignof work?

OOP & Classes Memory Management Memory Management

What is the difference between a memory leak and a resource leak?

Advanced
A memory leak is failing to free heap memory. A resource leak is more general—failing to release any acquired resource: file handles, sockets, mutex locks, database connections, or OS handles. RAII addresses both by tying resource release to object destruction, so any acquired resource is freed automatically when its owner goes out of scope.
{
    std::ofstream f("log.txt"); // RAII: file closed at scope end
}   // f's destructor releases the file handle
Real-world example Forgetting to close file handles exhausts the OS descriptor limit; RAII wrappers prevent it.

Common follow-ups: How does RAII fix resource leaks? | Give examples of non-memory resources.

RAII & Smart Pointers Exception Handling Memory Management

What causes a stack overflow?

Intermediate
A stack overflow happens when the call stack exceeds its size limit—commonly from very deep or infinite recursion, or allocating very large local arrays/objects on the stack. It typically crashes the program. Fixes include converting recursion to iteration, reducing recursion depth, or allocating large data on the heap.
void recurse() { recurse(); } // infinite recursion -> stack overflow
Real-world example A recursive tree traversal on a deeply unbalanced tree overflows the stack and crashes.

Common follow-ups: How do you avoid stack overflow? | Why allocate large arrays on the heap?

Memory Management References & Pointers Memory Management