Skip to the page

Programming basics · core

Stack, heap, strings and static in C

Know where each variable lives and how long it lives. Many C bugs come from returning stack memory or changing a string literal.

The notes

What you must know

  • Stack: a frame for each function call with locals, parameters and return address. Freed automatically on return. Fast, and small.
  • Heap: memory asked for at runtime with malloc, calloc, realloc (new in C++), kept until free (delete). Use it when the size is known only at runtime or the data must outlive the function.
  • Heap memory in this sense is not the heap data structure. Stack memory must not be freed with free.
  • Returning the address of a local array gives a dangling pointer. The memory is invalid after return. It may seem to work by luck. Fix: the caller passes a buffer and its size, or malloc inside (and the caller frees), or a static buffer (not safe for threads or repeat calls).
  • Use snprintf with a size to avoid overflow.
  • static local: created and initialised once and keeps its value between calls. An ordinary local is new on every call. A global is shared. Uninitialised globals and statics start at 0; an uninitialised local holds garbage.
  • static on a global variable or function makes it visible only in that .c file.
  • char a[] = "hello" is an array with its own copy (6 bytes with the ending \0). char *b = "hello" points to a literal that is usually read-only; changing it is undefined and usually crashes. Use const char *. Compare strings with strcmp, not ==.

The red pen

Common traps: mistake → fix

  • Mistake: It works when I run it, so it is fine

    Fix: a dangling pointer is undefined behaviour.

  • Mistake: static means constant

    Fix: it means one copy with a long life.

  • Mistake: sizeof("hello") is 5

    Fix: it is 6, with the ending \0.

  • Mistake: Compare strings with ==

    Fix: compare addresses; use strcmp.

Easy to hard

Questions interviewers ask, easy to hard

  1. Explain stack and heap memory.
  2. This function returns the address of a local array. What is wrong?
  3. What does this static counter code print?
  4. Why does changing a string literal crash?

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