Dynamic Memory Control
Core Memory Allocation Functions
malloc() Function
Allocates a specified number of bytes in heap memory without initialization.
void* malloc(size_t size);
calloc() Function
Allocates memory and initializes all bytes to zero.
void* calloc(size_t num_elements, size_t element_size);
realloc() Function
Resizes previously allocated memory block.
void* realloc(void* ptr, size_t new_size);
Memory Allocation Workflow
graph TD
A[Allocate Memory] --> B{Allocation Successful?}
B -->|Yes| C[Use Memory]
B -->|No| D[Handle Error]
C --> E[Free Memory]
Practical Memory Management Example
#include <stdio.h>
#include <stdlib.h>
int main() {
// Dynamic array allocation
int *dynamic_array = NULL;
int size = 5;
// Allocate memory
dynamic_array = (int*) malloc(size * sizeof(int));
if (dynamic_array == NULL) {
printf("Memory allocation failed\n");
return 1;
}
// Initialize array
for (int i = 0; i < size; i++) {
dynamic_array[i] = i * 10;
}
// Resize array
dynamic_array = realloc(dynamic_array, 10 * sizeof(int));
if (dynamic_array == NULL) {
printf("Memory reallocation failed\n");
return 1;
}
// Free memory
free(dynamic_array);
return 0;
}
Memory Allocation Strategies
Strategy |
Description |
Use Case |
Eager Allocation |
Allocate all needed memory upfront |
Fixed-size structures |
Lazy Allocation |
Allocate memory as needed |
Dynamic data structures |
Incremental Allocation |
Gradually increase memory |
Growing collections |
Common Memory Control Techniques
1. Null Pointer Checks
Always verify memory allocation success.
2. Memory Boundary Tracking
Keep track of allocated memory size.
3. Avoid Double Free
Never free the same pointer twice.
4. Set Pointers to NULL
After freeing, set pointers to NULL.
Advanced Memory Management
Memory Pools
Preallocate a large memory block and manage sub-allocations.
Custom Allocators
Implement application-specific memory management.
Potential Pitfalls
- Memory leaks
- Dangling pointers
- Buffer overflows
- Fragmentation
- Valgrind
- AddressSanitizer
- Memory profilers
Conclusion
Effective dynamic memory control requires careful planning and consistent practices. LabEx recommends continuous learning and practice to master these techniques.