Skip to the page

Pointers and memory · core

Stack, heap, new and delete

Local variables live on the stack and die when the function returns. new puts an object on the heap, where it stays until you delete it. Most memory bugs come from getting this pairing wrong.

The notes

What you must know

  • Stack: each function call gets a frame with its locals, parameters and return address. It is freed automatically on return. It is fast but small (commonly 8 MB on Linux and 1 MB on Windows).
  • Heap (the free store): new gives memory that lives until delete. Use it when the size is known only at runtime or the object must outlive the function. This heap is not the heap data structure.
  • new gets the memory and then calls the constructor; delete calls the destructor and then frees the memory. malloc and free do not call constructors or destructors.
  • Pair them exactly: new with delete, new[] with delete[], malloc with free. Any other mix is undefined behaviour.
  • When new cannot get memory, it throws std::bad_alloc; it does not return null. delete on a null pointer does nothing.
  • Memory leak: memory from new that is never deleted, often because the only pointer was lost (p = nullptr;, or a return in the middle of the function). The program's memory keeps growing.
  • Dangling pointer: it points to memory that was deleted, or to a local that went out of scope. Using it, or deleting it twice, is undefined behaviour. It may seem to work by luck.
  • Returning the address of a local array is a classic bug. In C++, return a std::string or std::vector by value instead: the copy is usually skipped (elided) or turned into a cheap move.

The red pen

Common traps: mistake → fix

  • Mistake: new returns NULL when memory runs out

    Fix: it throws std::bad_alloc.

  • Mistake: delete works for arrays from new[]

    Fix: use delete[]; a mismatch is undefined.

  • Mistake: It printed the right value, so the dangling pointer is fine

    Fix: it is undefined behaviour and can break on the next call.

  • Mistake: free() is fine for memory from new

    Fix: it skips the destructor and is undefined.

Easy to hard

Questions interviewers ask, easy to hard

  1. Explain stack and heap memory. What goes where?
  2. What is the difference between new and malloc?
  3. What is a memory leak? What is a dangling pointer?
  4. This function returns the address of a local array. What is wrong, and how do you fix it in C++?

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview