Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 77 ยท C, C++ and Systems Interview Questions

C and C++: Pointers, Memory and Undefined Behavior

Answer C and C++ interview questions on stack versus heap, pointer arithmetic, dangling pointers, memory leaks and undefined behavior, with a memory simulator.

Pointer questions are the core of every C and C++ interview, and they are also useful for any language: they test whether you understand what a variable physically is. Expect "What is the difference between stack and heap?", "What does p + 1 do?", "What is a dangling pointer?" and the trick question "What does this code print?" where the right answer is "anything".

The C and C++ code in this lesson is read-only: real memory errors are exactly what you must not run in a sandbox. Instead, each idea has a stand-in, a small JavaScript simulator that models memory as numbered cells so you can watch the mistakes happen safely. The simulator is a teaching model, not a real allocator. For the full tutorials see Pointers, Pointer Arithmetic, Dynamic Memory, Memory Errors and Undefined Behavior.

Stack versus heap

Q: What is the difference between the stack and the heap?

Two regions of memory

Stack Local variables. Freed automatically on return.
Heap malloc and new. You free it.

Static data and code live elsewhere again.

1 / 2

Local variables live in a stack frame that is created when a function is called and destroyed when it returns. The heap is a pool you request from at runtime (malloc in C, new in C++); the memory stays valid until you release it. The stack is fast and self-cleaning but small, and its data dies with the function. The heap is large and long-lived but you are responsible for the lifetime, and mistakes there cause leaks and corruption.

C
int *make_on_heap(void) {
    int *p = malloc(sizeof *p);   // heap: survives the return
    *p = 42;
    return p;                     // caller must free(p)
}

int *make_on_stack(void) {
    int local = 42;
    return &local;                // BUG: local dies at the closing brace
}

Pointer arithmetic

Q: What does p + 1 mean for an int *p? It moves by one element, not one byte: the address increases by sizeof(int). The array indexing syntax is defined through it: a[i] means *(a + i). That is also why sizeof(a) / sizeof(a[0]) works only on a real array, not on a pointer that an array decayed into when passed to a function.

C
int a[4] = {10, 20, 30, 40};
int *p = a;                 // array decays to a pointer to a[0]
printf("%d\n", *(p + 2));   // 30, same as a[2]
printf("%td\n", &a[3] - &a[0]);   // 3: subtraction counts elements, type ptrdiff_t

Rules worth stating: arithmetic is only defined inside one array (or one past its end), comparing or subtracting pointers to unrelated objects is undefined, and you may not dereference the one-past-the-end pointer. void * has no element size, so standard C does not allow arithmetic on it.

JS Stand-in: pointer arithmetic scales by element size

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Dangling pointers, leaks and double frees

Q: What is a dangling pointer? A pointer that still holds an address after the memory it points to has ended its lifetime: because the heap block was freed, or the stack frame returned, or the object went out of scope. Using it is undefined behavior. It might "work" today because the bytes have not been reused yet, which is what makes the bug so nasty.

Q: What is a memory leak? Heap memory that is still allocated but no longer reachable by any pointer, so it can never be freed. A long-running server that leaks a little per request eventually runs out of memory.

Q: What is a double free? Calling free twice on the same block. It corrupts the allocator's bookkeeping and is a classic security vulnerability.

C
char *name = malloc(16);
strcpy(name, "Ada");
free(name);
printf("%s\n", name);     // use after free: undefined behavior
free(name);               // double free: undefined behavior
name = NULL;              // good habit: free(NULL) is safe, and a NULL deref fails loudly

Standard defenses: set pointers to NULL after freeing, pair every malloc with one clear owner, use tools (AddressSanitizer -fsanitize=address, Valgrind) in testing, and in C++ prefer RAII and smart pointers (see C++: RAII, Smart Pointers and Move Semantics).

The stand-in below keeps a table of live blocks, so it can report each mistake in words:

JS Stand-in: a heap with checks for common errors

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Undefined behavior

Q: What is undefined behavior (UB), and why is it dangerous? The language standard places no requirements on what the program does. It may crash, print garbage, appear to work, or be "optimized" into something surprising, because compilers assume UB never happens and are free to delete code that depends on it. A program that contains UB is wrong even if it passes every test today.

Common sources, which interviewers love to list:

  • Dereferencing NULL, dangling or uninitialized pointers.
  • Reading uninitialized local variables.
  • Signed integer overflow (INT_MAX + 1). Unsigned overflow is well defined (wraps).
  • Out-of-bounds array access, including buffer overflows.
  • Modifying a string literal, or modifying an object twice without a sequence point.
  • Data races in C++ and C11 threads.
  • Using an object after its lifetime ended, and violating strict aliasing.
C
int find(int *a, int n, int x) {
    for (int i = 0; i <= n; i++) {     // off-by-one: reads a[n]
        if (a[i] == x) return i;
    }
    return -1;
}

Distinguish three similar terms: undefined behavior (anything), unspecified behavior (one of several valid outcomes, such as the order function arguments are evaluated) and implementation-defined behavior (the compiler must document it, such as the size of int).

The last stand-in shows why a returned stack address is a dangling pointer: the frame is popped, and the next call reuses the same cells.

JS Stand-in: a stack frame reused after return

Press Run (or Ctrl + Enter) to see the console output here.

No output.

C++ exceptions, noexcept, threads, mutex versus semaphore, atomics and false sharing

Expert-level C++ interviews go beyond RAII and smart pointers into error handling and concurrency. The examples in this section are real C++23 compiled with GCC 15 on the site's runner (threads included), not stand-ins. Their output is deterministic, because interview answers about concurrency should never depend on luck.

How do exceptions work, and what is stack unwinding?

When code executes throw, C++ looks for a matching catch up the call stack. On the way it performs stack unwinding: every local object between the throw and the handler is destroyed in reverse order of construction, so destructors run and RAII objects release their resources. That is why RAII is the foundation of exception safety.

Key rules:

  • Catch by reference (catch (const std::exception& e)), not by value, to avoid slicing and copies. Throw by value.
  • A catch (...) handles anything; order handlers from most specific to most general.
  • Never let an exception escape a destructor. Destructors are implicitly noexcept; throwing during unwinding calls std::terminate.
  • The exception-safety guarantees: basic (no leaks, invariants hold), strong (commit or rollback: the operation either fully succeeds or leaves state unchanged) and no-throw (never fails: swap, move, destructors).
  • Exceptions are slow when thrown (microseconds) and nearly free when not thrown on modern ABIs, so use them for exceptional errors, not for normal control flow. Many codebases (games, embedded) disable them and use error codes or std::expected instead.

What does noexcept do, and why does it matter for move?

noexcept promises a function will not throw. If it does, std::terminate is called. The compiler may generate better code, but the real importance is library behavior: std::vector must keep the strong guarantee when it grows. If the element's move constructor is noexcept, it moves elements into the new buffer; if it could throw, the vector falls back to copying (std::move_if_noexcept), because a throwing move would leave the old buffer half-moved. A forgotten noexcept on a move constructor therefore silently makes vector growth slower. Mark moves, swaps and destructors noexcept when they truly cannot throw. noexcept(expression) is also an operator that tests a condition at compile time.

C++ Real C++: unwinding order and the cost of a missing noexcept

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Read the output: g2 is released before g1, because unwinding destroys objects in reverse order, and the Slow vector made copies where Fast made moves.

How do you start threads and avoid data races?

std::thread starts a thread running a callable. You must join() or detach() it before it is destroyed, or the program terminates. std::jthread (C++20) joins automatically in its destructor and supports cooperative cancellation through a std::stop_token, so prefer it. A data race is two threads accessing the same memory, at least one writing, with no synchronization: it is undefined behavior, not just a wrong number. Two ways to fix a shared counter: protect it with a std::mutex, or make it a std::atomic. Use std::lock_guard or std::scoped_lock (which locks several mutexes without deadlock) so the lock is released even on exceptions.

Mutex versus semaphore

The classic comparison, in four lines:

  • A mutex provides mutual exclusion: only the thread that locked it may unlock it (it has an owner). Use it to protect a critical section.
  • A semaphore is a counter with acquire (decrement, wait if zero) and release (increment). Any thread can release; there is no owner. Use it for signaling between threads (a binary semaphore) or to limit concurrent access to a pool of N resources (a counting semaphore).
  • A mutex is not just a binary semaphore: ownership enables priority inheritance and tells you who holds the lock.
  • A condition variable (with a mutex) waits for an arbitrary predicate; a semaphore is the simpler tool when the condition is a count.
C++ Real C++: mutex, atomic and semaphores

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

What are atomics and memory orders?

std::atomic<T> makes operations on one variable indivisible and, depending on the memory order, controls how other memory operations may be reordered around it:

  • memory_order_relaxed: only the atomicity of this one variable, no ordering of other memory. Fine for counters.
  • memory_order_acquire (on loads) and memory_order_release (on stores): a release store publishes every write made before it to any thread whose acquire load reads that value. This is how you hand a prepared object to another thread.
  • memory_order_seq_cst (the default): one single global order of all such operations. Easiest to reason about and a little slower on some CPUs.
  • Compare-and-swap (compare_exchange_weak/strong) is the building block of lock-free structures; weak may fail spuriously and belongs in a loop. Beware the ABA problem: a value changes A to B and back to A, and the CAS thinks nothing changed.
  • volatile is not a synchronization tool in C++ (it only stops the compiler from optimizing accesses away; it gives no atomicity or ordering).

What is false sharing?

CPUs move memory in cache lines (typically 64 bytes). If two threads write to different variables that sit in the same cache line, the line bounces between the cores' caches even though there is no logical sharing, and performance can collapse. This is false sharing. The fix is to give each hot variable its own cache line: alignas(64) (or std::hardware_destructive_interference_size), padding, or per-thread counters merged at the end. Only measurement on real multi-core hardware shows the speed difference; the sandbox here has one CPU, so the next program shows the layout that causes or prevents it.

C++ Real C++: counters sharing a cache line versus padded counters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

A thread-safe design question often ends with: "how would you count events from many threads quickly?" The answer: keep a per-thread counter (padded to its own cache line) and add them up when asked, instead of hammering one shared atomic.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. For int *p, what does p + 2 compute?

    Pointer arithmetic is scaled by the size of the pointed-to type, which is why a[i] equals *(a + i).
  2. 2. Which one is a dangling pointer?

    A dangling pointer holds the address of memory whose lifetime has ended. NULL is a defined, checkable value, and live objects are fine.
  3. 3. Why is a program with undefined behavior wrong even if it seems to work?

    UB means no guarantees at all. Optimizers rely on that, so a bug that is invisible today can break after a harmless-looking change.
  4. 4. Which of these is NOT undefined behavior in C?

    Unsigned arithmetic is defined to wrap modulo 2^N. The other three have no defined behavior.

Summary

  • The stack holds locals and is freed automatically; the heap holds malloc/new memory that you must release exactly once.
  • p + n moves by n elements; a[i] is *(a + i).
  • Dangling pointers, leaks, double frees and buffer overflows are lifetime or bounds errors; set pointers to NULL, define one owner, and test with sanitizers.
  • Undefined behavior means no guarantees; never rely on "it worked when I ran it".
  • In C++, prefer RAII and smart pointers over manual new and delete.
  • Exceptions unwind the stack and run destructors in reverse order; never throw from a destructor, catch by reference, and mark moves and swaps noexcept so containers move instead of copy.
  • A mutex has an owner and guards a critical section; a semaphore is an ownerless counter for signaling or limiting concurrency; atomics fix one variable and memory orders control visibility.
  • False sharing happens when threads write to different variables on one cache line; pad hot data with alignas(64) or use per-thread counters.

Next: C++: RAII, Smart Pointers and Move Semantics.