Quiz 2

C Memory Layout — Stack, Heap, Data, Text

601 words
3 min read
Python Week 1: the first filter for runtime behavior
Visual companion
Python
Type and operator map

Python Week 1: the first filter for runtime behavior

View
Revision summary

What this note is really saying

Short form

# C Memory Layout — Stack, Heap, Data, Text ## 🎯 Learning Objectives - Draw the memory layout of a C program - Differentiate between stack and heap allocation - Explain the lifetime of static, automatic, and allocated variables - Recognize common memory errors * * * ## 1. Process Memory Layout *(Diagram)* ### 1.1 S...

C Memory Layout — Stack, Heap, Data, Text

🎯 Learning Objectives

  • Draw the memory layout of a C program
  • Differentiate between stack and heap allocation
  • Explain the lifetime of static, automatic, and allocated variables
  • Recognize common memory errors

1. Process Memory Layout

(Diagram)

1.1 Segment Descriptions

SegmentContentsLifetimeGrowthExample
TextProgram code (instructions)Entire programFixedint main() { ... }
DataInitialized globals/staticsEntire programFixedint x = 10;
BSSUninitialized globals/staticsEntire programFixedint y;
HeapDynamically allocated memorymalloc→freeUpwardmalloc(100)
StackLocal variables, function framesFunction call→returnDownwardint z;

1.2 Example: Where Variables Live

c
#include <stdio.h>
#include <stdlib.h>
int global_init = 42;          // Data segment
int global_uninit;              // BSS segment
void func() {
    int local = 10;             // Stack
    static int static_var = 5;  // Data segment
    int *heap_var = malloc(sizeof(int));  // Heap (pointer on stack)
    *heap_var = 100;
    printf("Code (text):   %p\n", (void*)func);
    printf("Global init:   %p\n", (void*)&global_init);
    printf("Global uninit: %p\n", (void*)&global_uninit);
    printf("Static:        %p\n", (void*)&static_var);
    printf("Heap:          %p\n", (void*)heap_var);
    printf("Local (stack): %p\n", (void*)&local);
    free(heap_var);
}
Output (addresses will vary):
pseudo
Code (text):   0x400500
Global init:   0x601040
Global uninit: 0x601060
Static:        0x601044
Heap:          0x1a26010
Local (stack): 0x7ffd5a1e4b2c

2. Stack vs Heap Comparison

AspectStackHeap
SpeedFast (allocation = SP adjust)Slow (malloc must find free block)
SizeSmall (typically 1-8 MB)Large (limited by RAM)
LifetimeAutomatic (function scope)Manual (malloc → free)
Memory managementAutomaticManual (or GC)
FragmentationNoneExternal fragmentation
Thread safetyPer-thread (each thread has own stack)Shared (needs synchronization)

3. Common Memory Errors

3.1 Stack Overflow

c
void infinite_recursion() {
    int arr[1000];  // 4KB each call
    infinite_recursion();  // Eventually overflows stack
}

3.2 Buffer Overflow

c
char buffer[10];
strcpy(buffer, "This string is way too long!");  // Overwrites adjacent memory

3.3 Use-After-Free

c
int *p = malloc(sizeof(int));
free(p);
*p = 42;  // Undefined behavior! p is dangling

3.4 Memory Leak

c
void leak() {
    int *p = malloc(1000000);  // Allocated
    // Never freed!
}

4. 📝 Practice Questions

Q1: Where are the following variables stored? int a = 5; static int b; int c; void f() { int d; static int e; }
Answer: a: Data segment (initialized global). b: BSS (uninitialized static). c: BSS (uninitialized global). d: Stack (local in function). e: Data segment (initialized to 0 static local). Q2: Why is stack allocation faster than heap allocation?
Answer: Stack allocation is just adjusting the stack pointer (one instruction). Heap allocation must search for a suitable free block, possibly splitting or coalescing blocks, and may involve system calls (brk/sbrk) to extend the heap. Q3: What happens when the stack grows into the heap?
Answer: This causes a stack overflow (SEGFAULT). The OS detects the invalid memory access and terminates the program. In modern OS with virtual memory, the stack and heap are far apart with guard pages. Q4: How does a memory leak affect a long-running program?
Answer: Each leak reduces available heap memory. Over time, the program's memory usage grows (memory bloat), eventually exhausting system memory or triggering OOM (Out-of-Memory) killer. This is especially critical in servers and embedded systems. Q5: What is the difference between BSS and Data segments?
Answer: Both store global/static data. BSS stores uninitialized variables (set to 0 at runtime). Data stores initialized variables (values loaded from the executable file). BSS saves disk space because it doesn't need to store zeros in the executable.

5. 🔗 Cross-References

  • Week 3 - Pointers: Pointer arithmetic and memory access
  • Week 5 - Dynamic Memory: malloc/calloc/free details
  • BSCS4022 (OS): Process memory management, virtual memory Join Discord NextControl Flow & Arrays
Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.