Post

Stack VS Heap in C

Stack VS Heap in C

Stack VS Heap in C

Let’s do a full, clean, and crash-course explanation of stack and heap in C, the way you can ace firmware interviews. I’ll keep it practical for embedded firmware.


1. What is Stack?

  • Stack memory is automatic memory.
  • Used for: local variables, function calls, return addresses.
  • Managed by compiler.
  • LIFO (Last In, First Out) → last function called is first to return.
  • Size is usually small, limited by OS / MCU.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
#include <stdio.h>

void func() {
    int a = 10; // stored in stack
    int b = 20; // stored in stack
    printf("%d %d\n", a, b);
}

int main() {
    func();
    return 0;
}

✅ Notes:

  • Variables a and b exist only during function execution.
  • Memory is automatically released when function exits.

Stack Pros & Cons

ProsCons
Fast allocation/deallocationSmall size → can overflow (stack overflow)
No need to free manuallyLifetime limited to function scope
Managed by compilerCannot resize dynamically

2. What is Heap?

  • Heap memory is dynamic memory.
  • Managed by the programmer using malloc / free.
  • Used for: dynamic data structures, large arrays, buffers.
  • Larger than stack but slower allocation.
  • Lifetime controlled manually, exists until free() is called.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <stdio.h>
#include <stdlib.h>

int main() {
    int *ptr = (int*)malloc(sizeof(int)); // allocate on heap
    if(ptr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }
    *ptr = 100;
    printf("%d\n", *ptr);

    free(ptr); // release heap memory
    return 0;
}

✅ Notes:

  • Heap memory persists beyond function scope.
  • You must free it manually, or you get memory leaks.

Heap Pros & Cons

ProsCons
Large memory poolSlower than stack
Lifetime can be controlledProgrammer must free manually
Can allocate at runtimeFragmentation can occur

3. Stack vs Heap – Quick Comparison

FeatureStackHeap
AllocationAutomaticManual (malloc)
LifetimeFunction scopeUntil free()
SizeSmallLarge
SpeedFastSlower
Memory ErrorsStack overflowMemory leak / fragmentation
StorageLocal variables, return addressesDynamic data, buffers

4. Common Interview Questions

  1. Difference between stack and heap.
  2. What happens if stack overflows?
  3. How to avoid memory leaks in heap?
  4. When to use stack vs heap in firmware?
  5. How does recursive function affect stack?

5. Firmware Tip

  • Prefer stack for small, temporary variables.
  • Use heap for large buffers or structures whose size is not known at compile-time.
  • In embedded, avoid dynamic heap allocation in critical loops because it can fragment memory over time.

This post is licensed under CC BY 4.0 by the author.