Safe Memory Handling
Memory Safety Principles
Understanding Memory Risks
- Buffer overflows
- Memory leaks
- Dangling pointers
- Uninitialized memory access
Defensive Memory Allocation
Allocation Validation
int *safeAllocation(size_t size) {
int *ptr = malloc(size);
if (ptr == NULL) {
fprintf(stderr, "Memory allocation failed\n");
exit(EXIT_FAILURE);
}
return ptr;
}
Memory Leak Prevention
Systematic Memory Management
graph TD
A[Allocate Memory] --> B{Check Allocation}
B -->|Success| C[Use Memory]
B -->|Failure| D[Handle Error]
C --> E[Free Memory]
E --> F[Set Pointer to NULL]
Safe Deallocation Techniques
Pointer Nullification
void safeFree(int **ptr) {
if (ptr != NULL && *ptr != NULL) {
free(*ptr);
*ptr = NULL;
}
}
Memory Handling Strategies
Strategy |
Description |
Best Practice |
Null Checks |
Validate pointers |
Always check before use |
Boundary Checks |
Prevent overflows |
Use size limits |
Initialization |
Avoid garbage values |
Initialize before use |
Advanced Safety Techniques
Using Valgrind for Memory Debugging
valgrind --leak-check=full ./your_program
Common Memory Safety Patterns
Safe Dynamic Array Management
typedef struct {
int *data;
size_t size;
size_t capacity;
} SafeArray;
SafeArray* createSafeArray(size_t initial_capacity) {
SafeArray *arr = malloc(sizeof(SafeArray));
if (arr == NULL) return NULL;
arr->data = malloc(initial_capacity * sizeof(int));
if (arr->data == NULL) {
free(arr);
return NULL;
}
arr->size = 0;
arr->capacity = initial_capacity;
return arr;
}
void freeSafeArray(SafeArray *arr) {
if (arr != NULL) {
free(arr->data);
free(arr);
}
}
Memory Safety Rules
- Always check allocation results
- Free dynamically allocated memory
- Set pointers to NULL after freeing
- Avoid multiple frees
- Use memory debugging tools
LabEx Recommended Practices
At LabEx, we emphasize:
- Proactive memory management
- Defensive programming techniques
- Continuous learning and improvement
Error Handling Example
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char *buffer = NULL;
size_t buffer_size = 100;
buffer = malloc(buffer_size);
if (buffer == NULL) {
fprintf(stderr, "Memory allocation failed\n");
return EXIT_FAILURE;
}
// Safe string handling
strncpy(buffer, "Safe memory handling", buffer_size - 1);
buffer[buffer_size - 1] = '\0';
printf("%s\n", buffer);
free(buffer);
buffer = NULL;
return EXIT_SUCCESS;
}