Memory Allocation Fundamentals
Introduction to Memory Allocation
Memory allocation is a critical aspect of C programming that involves dynamically managing memory during program execution. In C, developers have direct control over memory management, which provides flexibility but also requires careful handling.
Types of Memory Allocation
C provides two primary memory allocation methods:
Allocation Type |
Keyword |
Memory Location |
Lifetime |
Characteristics |
Static Allocation |
Static |
Data Segment |
Entire Program |
Fixed Size, Compile-Time |
Dynamic Allocation |
malloc/calloc/realloc |
Heap |
Programmer-Controlled |
Flexible Size, Runtime |
Dynamic Memory Allocation Functions
malloc() Function
void* malloc(size_t size);
Allocates a specified number of bytes in the heap memory.
Example:
int *ptr = (int*) malloc(5 * sizeof(int));
if (ptr == NULL) {
fprintf(stderr, "Memory allocation failed\n");
exit(1);
}
calloc() Function
void* calloc(size_t num, size_t size);
Allocates memory and initializes all bytes to zero.
Example:
int *arr = (int*) calloc(10, sizeof(int));
realloc() Function
void* realloc(void* ptr, size_t new_size);
Resizes previously allocated memory block.
Example:
ptr = realloc(ptr, new_size * sizeof(int));
Memory Allocation Workflow
graph TD
A[Start Memory Allocation] --> B{Sufficient Memory?}
B -->|Yes| C[Allocate Memory]
B -->|No| D[Handle Allocation Failure]
C --> E[Use Allocated Memory]
E --> F[Free Memory]
F --> G[End]
Best Practices
- Always check allocation success
- Free dynamically allocated memory
- Avoid memory leaks
- Use appropriate allocation functions
Common Pitfalls
- Forgetting to free memory
- Accessing memory after freeing
- Buffer overflows
- Memory fragmentation
Memory Management with LabEx
LabEx recommends following systematic memory management techniques to ensure robust and efficient C programming. Understanding these fundamentals is crucial for developing high-performance applications.