Memory Best Practices
Memory Management Strategies
graph TD
A[Validate Allocations] --> B[Proper Deallocation]
B --> C[Avoid Dangling Pointers]
C --> D[Use Memory Tools]
Common Memory Management Techniques
Technique |
Description |
Benefit |
Null Checks |
Validate memory allocation |
Prevent segmentation faults |
Defensive Copying |
Create independent copies |
Reduce unintended modifications |
Memory Pooling |
Reuse memory blocks |
Improve performance |
Safe Allocation Pattern
#include <stdio.h>
#include <stdlib.h>
void* safe_malloc(size_t size) {
void *ptr = malloc(size);
if (ptr == NULL) {
fprintf(stderr, "Memory allocation failed\n");
exit(EXIT_FAILURE);
}
return ptr;
}
int main() {
int *data = (int*)safe_malloc(10 * sizeof(int));
// Use memory safely
for (int i = 0; i < 10; i++) {
data[i] = i;
}
free(data);
return 0;
}
Memory Leak Prevention
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int *data;
size_t size;
} SafeArray;
SafeArray* create_array(size_t size) {
SafeArray *arr = malloc(sizeof(SafeArray));
if (arr == NULL) return NULL;
arr->data = malloc(size * sizeof(int));
if (arr->data == NULL) {
free(arr);
return NULL;
}
arr->size = size;
return arr;
}
void free_array(SafeArray *arr) {
if (arr != NULL) {
free(arr->data);
free(arr);
}
}
int main() {
SafeArray *arr = create_array(10);
if (arr == NULL) {
fprintf(stderr, "Array creation failed\n");
return EXIT_FAILURE;
}
// Use array
free_array(arr);
return 0;
}
Memory Debugging Techniques
Valgrind Usage
## Compile with debug symbols
gcc -g -o program program.c
## Run with valgrind
valgrind --leak-check=full ./program
Advanced Memory Management
Smart Pointer Simulation
#include <stdlib.h>
typedef struct {
void *ptr;
void (*destructor)(void*);
} SmartPtr;
SmartPtr* create_smart_ptr(void *ptr, void (*destructor)(void*)) {
SmartPtr *smart_ptr = malloc(sizeof(SmartPtr));
if (smart_ptr == NULL) return NULL;
smart_ptr->ptr = ptr;
smart_ptr->destructor = destructor;
return smart_ptr;
}
void destroy_smart_ptr(SmartPtr *smart_ptr) {
if (smart_ptr != NULL) {
if (smart_ptr->destructor) {
smart_ptr->destructor(smart_ptr->ptr);
}
free(smart_ptr);
}
}
Key Recommendations
- Always validate memory allocations
- Free memory immediately when no longer needed
- Use memory debugging tools
- Implement proper error handling
- Consider memory-efficient data structures
Enhance your memory management skills with practical exercises on LabEx platform.