Skip to content
Learn Netverks

Lesson

Step 19/36 53% through track

stack-vs-heap

Stack vs heap

Last reviewed May 28, 2026 Content v20260528
Track mode
server_compiled
Means
Compiled runner
Reading
~1 min
Level
intermediate

This lesson

This lesson teaches Stack vs heap: the syntax, patterns, and safety habits you need before advancing in C.

Stack vs heap explains lifetimes—returning pointers to locals is a classic failure mode.

You will apply Stack vs heap in contexts like: Kernels, drivers, embedded devices, and performance libraries used by other languages.

Write C in main.c with int main(), click Run on server—the dev runner compiles with cc/gcc -std=c11 and runs the binary; read stderr for compile and linker errors (LEARNING_RUNNER_ENABLED=true).

When you can explain the previous lesson's ideas without copying starter code.

Choosing stack vs heap affects lifetime, performance, and bug surface. Contrast with Java where most objects live on the heap under GC.

Stack characteristics

  • Fast allocation/deallocation tied to function calls
  • Limited size—deep recursion or huge locals can overflow
  • Do not return pointers to local stack variables

Heap characteristics

  • Flexible size and lifetime across functions
  • Requires malloc/free discipline
  • Fragmentation and leaks if mismanaged

Important interview questions and answers

  1. Q: Return local array?
    A: Invalid—stack memory dies when the function returns; return heap memory or use caller-provided buffer.
  2. Q: When prefer stack?
    A: Small, short-lived values with known bounded size.

Self-check

  1. Why is returning &local_int dangerous?
  2. What error indicates stack overflow?

Pitfall: Never return a pointer to a local stack variable—the memory is invalid after the function returns. Use heap allocation or caller-provided buffers.

Interview prep

Return local array?

Invalid—the stack frame is destroyed on return; use heap allocation or caller buffer.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Playground

Runs on the configured server runner (dev: npm run runner with LEARNING_RUNNER_ENABLED=true). Output appears below the editor.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • Return local ptr?
  • Stack overflow?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump