Memory Allocation
Understanding static and dynamic memory management
🧠 Memory Allocation Types
Memory allocation manages how programs use computer memory. Static allocation happens at compile-time, while dynamic allocation occurs during runtime execution.
// Static allocation (compile-time)
int static_array[100];
// Dynamic allocation (runtime)
int *dynamic_array = malloc(100 * sizeof(int));
Memory Types
Stack Memory
Automatic local variables
int local_var = 10;
Heap Memory
Dynamic allocation area
int *ptr = malloc(sizeof(int));
Global Memory
Global and static variables
int global_var;
Code Memory
Program instructions
void function() { }
🔹 Static vs Dynamic Allocation
Static allocation reserves memory at compile-time with fixed size, while dynamic allocation happens at runtime with flexible sizing. Static variables live on the stack and have predetermined lifetimes; dynamic variables use the heap for flexible management. Choose static allocation for small, fixed-size data; use dynamic allocation for large or variable-sized data structures. Understanding these differences helps you design efficient memory strategies for different programming scenarios and requirements.
#include <stdio.h>
#include <stdlib.h>
int main() {
// Static allocation - size fixed at compile time
int static_array[5] = {1, 2, 3, 4, 5};
// Dynamic allocation - size determined at runtime
int size = 5;
int *dynamic_array = malloc(size * sizeof(int));
// Initialize dynamic array
for (int i = 0; i < size; i++) {
dynamic_array[i] = (i + 1) * 10;
}
printf("Static array: ");
for (int i = 0; i < 5; i++) {
printf("%d ", static_array[i]);
}
printf("\nDynamic array: ");
for (int i = 0; i < size; i++) {
printf("%d ", dynamic_array[i]);
}
// Free dynamic memory
free(dynamic_array);
return 0;
}
Output:
Static array: 1 2 3 4 5 Dynamic array: 10 20 30 40 50
🔹 Memory Layout
C programs organize memory into distinct regions: stack, heap, data segment, and code segment. The stack stores local variables and function parameters with automatic cleanup. The heap provides dynamic allocation controlled by programmer. The data segment stores global and static variables. Understanding memory layout helps diagnose issues and optimize program performance. This knowledge is essential for writing efficient, secure C programs that manage resources responsibly.
#include <stdio.h>
#include <stdlib.h>
int global_var = 100; // Global memory
static int static_var = 200; // Global memory
void show_memory_layout() {
int local_var = 300; // Stack memory
int *heap_var = malloc(sizeof(int)); // Heap memory
*heap_var = 400;
printf("Memory Addresses:\n");
printf("Global variable: %p\n", &global_var);
printf("Static variable: %p\n", &static_var);
printf("Local variable: %p\n", &local_var);
printf("Heap variable: %p\n", heap_var);
printf("Function address: %p\n", show_memory_layout);
free(heap_var);
}
int main() {
show_memory_layout();
return 0;
}
Output:
Memory Addresses: Global variable: 0x601040 Static variable: 0x601044 Local variable: 0x7fff5fbff6ac Heap variable: 0x1234567 Function address: 0x400526
🔹 Memory Allocation Best Practices
Follow proven guidelines for effective and safe memory management in your C programs. Always allocate slightly more memory than needed to accommodate growth. Check return values of allocation functions for NULL. Use consistent naming conventions for allocated pointers. Document which functions allocate and free memory clearly. Implement error handling for allocation failures gracefully. These practices create maintainable, robust programs less prone to crashes and memory-related bugs.
✅ Good Practices
- Always check malloc return: Verify allocation succeeded
- Free allocated memory: Prevent memory leaks
- Set pointers to NULL: After freeing memory
- Use appropriate size: Allocate only what you need
❌ Common Mistakes
- Memory leaks: Forgetting to call free()
- Double free: Calling free() twice
- Use after free: Accessing freed memory
- Buffer overflow: Writing beyond allocated space