100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
C

Memory Management in C

Understand C's memory layout — text, data, heap, and stack segments — and when to choose stack vs heap allocation.

Advanced CIntermediate13 min readJul 7, 2026
Analogies

1. Introduction

C gives programmers direct, low-level control over memory, which is both its greatest strength and its most common source of bugs. Unlike languages with automatic garbage collection, a C program is responsible for understanding where its data lives and, for some of it, when that data is freed. Every running C program's address space is conceptually divided into distinct memory segments — text, data (including BSS), heap, and stack — each with different lifetimes, growth behavior, and performance characteristics. Understanding this layout is foundational for writing efficient, correct programs and for reasoning about bugs like stack overflows, memory leaks, and dangling pointers.

🏏

Cricket analogy: C's manual memory control is like a captain personally managing which players bat, field, or rest rather than relying on an auto-selector, with segments like the playing XI (stack), reserves (heap), and permanent staff (data) each behaving differently.

2. Syntax

There is no single "syntax" for memory segments since they are a runtime/OS concept, but each segment corresponds to recognizable code patterns:

🏏

Cricket analogy: There's no rulebook page labeled 'memory segments,' but just as a scorer recognizes an over is a maiden from the pattern of dots rather than a label, a programmer recognizes each segment from the code pattern that produces it.

c
int global_initialized = 42;      /* data segment */
static int global_uninitialized;   /* bss segment  */

void demo(void) {
    int local_var = 10;            /* stack segment */
    int *heap_ptr = malloc(sizeof(int) * 100); /* heap segment */
    free(heap_ptr);
}

3. Explanation

A typical process image (the exact layout is platform- and OS-dependent, but the conceptual model is consistent) contains: the **text/code segment**, which holds the compiled machine instructions and is typically read-only and shared between processes running the same executable; the **data segment**, which holds global and static variables that are explicitly initialized with a non-zero value; the **BSS segment**, which holds global and static variables that are uninitialized or initialized to zero (the OS zero-fills this region at load time, so it doesn't need to be stored in the executable file); the **heap**, a region used for dynamic memory allocated at runtime via malloc/calloc/realloc, which conceptually grows upward toward higher addresses as more memory is requested; and the **stack**, used for function call frames — local variables, parameters, and return addresses — which conceptually grows downward from high addresses and shrinks automatically as functions return.

🏏

Cricket analogy: The text segment is like the fixed laws of cricket printed in the rulebook, the data segment is like a team's pre-set batting order printed on the card, BSS is like blank scorecards ready to be filled to zero, the heap is like extra players called up as the tournament grows, and the stack is like the current over's ball-by-ball sequence that clears itself once the over ends.

Stack allocation is extremely fast: it's just a matter of moving a stack pointer, and memory is reclaimed automatically the moment a function returns, with no possibility of a leak. Its downsides are a fixed, relatively small size (often a few MB, configurable but limited) and automatic deallocation, meaning you cannot return a pointer to a local stack variable and expect it to remain valid. Heap allocation, by contrast, is explicit and manual: you call malloc, calloc, or realloc to reserve memory that persists until you call free on it (or the program ends). This makes the heap suitable for data whose size isn't known at compile time, or whose lifetime must outlive the function that created it, at the cost of being slower (due to allocator bookkeeping) and requiring careful management to avoid memory leaks (forgetting to free), dangling pointers (using memory after it's freed), and fragmentation (heap space split into many small, non-contiguous free blocks over time, making large allocations harder to satisfy even when total free memory is sufficient).

🏏

Cricket analogy: The stack is like a quick single run between wickets, fast and automatically over once completed, but limited by the pitch's length, while the heap is like arranging a benefit match manually — flexible but requiring you to personally book the ground (free it) or risk it sitting unused (a leak).

For completeness, the three core dynamic-memory functions are: malloc(size), which reserves size bytes of uninitialized memory and returns a pointer (or NULL on failure); calloc(n, size), which reserves space for n elements of size bytes each and zero-initializes the entire block; realloc(ptr, new_size), which resizes a previously allocated block, possibly moving it, and preserves existing contents up to the smaller of the old and new sizes; and free(ptr), which releases memory back to the heap allocator so it can be reused. Every successful malloc/calloc/realloc call should eventually be matched with exactly one free call.

🏏

Cricket analogy: malloc(size) is like requesting a fresh, unmarked scorecard of a given size; calloc(n, size) is like requesting n pre-zeroed scorecards for a whole tournament; realloc resizes an existing scorecard mid-series while keeping past entries; and free() is like returning the scorecard to the pavilion once the match series ends.

Two opposite failure modes to watch for: a **stack overflow**, caused by excessive recursion depth or very large local arrays (e.g., int buffer[10000000]; inside a function) that exceeds the stack's fixed size and crashes the program; and **heap fragmentation/leaks**, caused by repeated allocate/free cycles of varying sizes or by simply forgetting to free memory, which can degrade performance or exhaust available memory over a long-running program's lifetime.

Tip: as a rule of thumb, prefer stack allocation for small, fixed-size, short-lived data (fast and leak-proof), and reach for heap allocation only when the size is unknown until runtime, the data is large, or it must outlive the function that created it.

4. Example

c
#include <stdio.h>
#include <stdlib.h>

int global_data = 100;       /* data segment: initialized global */
static int global_bss;        /* bss segment: uninitialized global */

void stack_demo(void) {
    int local_array[5] = {1, 2, 3, 4, 5};  /* stack: freed automatically */
    printf("Stack address of local_array: %p\n", (void *)local_array);
}

void heap_demo(int n) {
    int *heap_array = malloc(n * sizeof(int)); /* heap: manual lifetime */
    if (heap_array == NULL) {
        fprintf(stderr, "Allocation failed\n");
        return;
    }
    for (int i = 0; i < n; i++) {
        heap_array[i] = i * i;
    }
    printf("Heap address of heap_array: %p\n", (void *)heap_array);
    printf("heap_array[3] = %d\n", heap_array[3]);
    free(heap_array);   /* must free manually */
    heap_array = NULL;  /* avoid dangling pointer */
}

int main(void) {
    stack_demo();
    heap_demo(5);
    printf("global_data (data seg) = %d\n", global_data);
    printf("global_bss (bss seg)  = %d\n", global_bss);
    return 0;
}

5. Output

text
Stack address of local_array: 0x7ffee2a1c9d0
Heap address of heap_array: 0x55d8f3a1a2a0
heap_array[3] = 9
global_data (data seg) = 100
global_bss (bss seg)  = 0

(Actual addresses vary by run, OS, and ASLR settings;
note heap and stack addresses are far apart in the address space.)

6. Key Takeaways

  • A C process's address space is conceptually divided into text/code, data, BSS, heap, and stack segments.
  • Text holds instructions; data holds initialized globals/statics; BSS holds zero/uninitialized globals/statics.
  • The stack holds function call frames and local variables; it grows/shrinks automatically and is very fast.
  • The heap holds dynamically allocated memory (malloc/calloc/realloc) with manual, programmer-controlled lifetime via free.
  • Stack memory is limited and auto-freed on function return; heap memory is larger but must be explicitly freed.
  • Stack overflow (excess recursion/large locals) and heap leaks/fragmentation are the classic failure modes of each region.

Practice what you learned

Was this page helpful?

Topics covered

#CProgrammingStudyNotes#Programming#MemoryManagementInC#Memory#Management#Syntax#Explanation#StudyNotes#SkillVeris#ExamPrep