Where is the heap?
related to the previous post about the stack
In a C program, the heap is located in a specific region of the process's virtual memory space. Here's where it sits in the typical memory layout:
Memory Layout (from low to high addresses):
Text/Code segment - Contains the executable code
Data segment - Contains initialized global/static variables
BSS segment - Contains uninitialized global/static variables
Heap - Grows upward toward higher addresses
Memory mapping segment - For memory-mapped files, shared libraries
Stack - Grows downward toward lower addresses
Heap Characteristics:
Location: Positioned above the BSS segment, typically starting right after it
Growth direction: Expands upward (toward higher memory addresses)
Management: Controlled by functions like
malloc(),calloc(),realloc(), andfree()Size: Dynamic - grows and shrinks during program execution
Leaking memory on the Heap: What Happens on Program Termination:
Complete Memory Cleanup:
The OS deallocates the entire virtual address space assigned to your process
All heap memory (leaked or not) gets freed
Stack, data segments, code segments - everything gets cleaned up
No leaked memory persists after program exit
Why This Happens:
Process Isolation:
Each process has its own isolated virtual address space
When a process dies, the OS simply destroys that entire address space
This is a fundamental part of process management in modern operating systems
OS Memory Management:
The OS maintains page tables mapping virtual to physical memory for each process
On process termination, these mappings are removed
Physical memory pages are returned to the system's free memory pool
Why memory leaks still matter
During Program Execution:
Memory leaks still matter because they can cause your program to run out of memory
Long-running programs can exhaust available memory
Performance degradation from excessive memory usage
File Descriptors cleanup:
Automatic Cleanup on Process Exit:
The OS automatically closes all open file descriptors when a process terminates
This includes regular files, sockets, pipes, device files, etc.
The kernel maintains a per-process file descriptor table that gets destroyed on exit
Not a good cleanup?
System V IPC objects (on some systems):
Shared memory segments created with
shmget()Semaphores created with
semget()Message queues created with
msgget()These might persist after process exit on some systems (though many modern systems clean these up too)
But for typical programming:
Files, sockets, pipes → automatically cleaned up
Heap memory → automatically cleaned up
Stack, globals, etc. → automatically cleaned up
A small supplement regarding external variables in C.
(They are not on the heap. Shown in the blue section)
At runtime, this memory is directly accessed by functions via absolute addresses. No copying or passing is required — they are directly referenced in the generated machine code.



