GCGY Beta v1.0.1
GrowCodeEngineering
← Back to Hub
Back to Topics
c / c-fundamentals
22 mins

C Level 6: Dynamic Heap Allocation (malloc/free)

Why This Matters: Stack memory is fixed and temporary. Dynamic heap allocation allows programs to request arbitrary memory sizes at runtime.
## Stack vs Heap Memory Allocation

- **Stack**: Managed automatically by CPU call frames. Fast, but fixed size. Cleared on return.
- **Heap**: Managed manually by programmer via stdlib. Persists until explicitly freed.

### Heap Management Functions (`<stdlib.h>`)
- `malloc(bytes)`: Allocates uninitialized memory on Heap.
- `calloc(num, size)`: Allocates zero-initialized memory.
- `free(ptr)`: Releases heap block back to OS.
MENTAL MODEL & MEMORY LAYOUT
STACK vs HEAP MEMORY MODEL:
STACK: [ main() frame ] ──► ptr (pointer holding 0x9000)
                              │
HEAP:                         ▼
                            [ Allocated Heap Memory (0x9000) ]
                            (Persists until free(ptr) is called)
COMMON PITFALLS TO AVOID
  • Memory Leak: Calling malloc() without calling free() before program exits.
  • Dangling Pointer: Accessing pointer memory after calling free(). Fix: set ptr = NULL.
  • Missing NULL check after malloc allocation call.
Safe Heap Allocation Pattern
#include <stdio.h>
#include <stdlib.h>

int main() {
    int *arr = (int*) malloc(5 * sizeof(int));
    if (arr == NULL) {
        printf("Allocation failed!\n");
        return 1;
    }
    arr[0] = 50;
    printf("Heap value: %d\n", arr[0]);
    free(arr); // MANDATORY
    arr = NULL; // Prevent dangling pointer
    return 0;
}

Checks for allocation NULL failure, uses dynamic memory, frees heap block, and nullifies pointer.

CONCEPT MASTERY CHECKPOINT

What happens if a program calls `malloc()` continuously in a loop without ever calling `free()`?

NEXT RECOMMENDED LESSON
C Level 7: Structures & Unions
Continue Path
Challenge: Allocate a single integer on heap using malloc(), assign value 500, print it, and call free().
C Level 6: Dynamic Heap Allocation (malloc/free)
1
2
3
4
5
6
7
8
9
10
11
12
13
No test case execution results available yet. Click "Run Code" to evaluate your solution.