C provides low-level control over memory, allowing programmers to manage how memory is allocated, used, and released.
Understanding memory internals helps in writing efficient and safe programs.
When a C program is executed, memory is divided into several segments:
Contains compiled program instructions
Read-only
Prevents accidental modification of code
Stores global and static variables that are initialized.
Stores uninitialized global and static variables.
Automatically initialized to zero
Used for dynamic memory allocation
Memory allocated using malloc(), calloc(), realloc()
Grows upward
Stores local variables, function parameters, return addresses
Memory is automatically managed
Follows LIFO order
Grows downward
| Feature | Stack | Heap |
|---|---|---|
| Allocation | Automatic | Manual |
| Speed | Faster | Slower |
| Size | Limited | Large |
| Deallocation | Automatic | Programmer controlled |
Allocates a block of memory
Does not initialize memory
Allocates multiple blocks
Initializes memory to zero
Resizes allocated memory
Releases allocated memory back to heap
Allocated memory not freed
Pointer refers to freed memory
Writing beyond allocated memory
Freeing the same memory twice
Always check malloc() return value
Free memory after use
Set pointers to NULL after freeing
Avoid accessing freed memory
C memory is divided into text, data, BSS, heap, and stack
Stack is automatic, heap is manual
Dynamic memory must be managed carefully
Poor memory handling leads to bugs and crashes
Take quizzes related to this topic and see where you stand!
Start Quiz Now