Invalid Free
memory
invalid free()
Description
The program attempts to free memory that was not allocated with malloc/calloc or has already been freed.
Common Causes
- Freeing a pointer that was not returned by malloc/calloc
- Freeing a pointer that has been modified since allocation
- Freeing memory allocated with a different allocator
Example of Error
Error Code
int main() {
int arr[10];
free(arr); // Invalid free - arr is stack-allocated
return 0;
}
Solution
Only free memory that was allocated with malloc, calloc, or realloc.
Corrected Code
int main() {
int *arr = malloc(10 * sizeof(int));
if (arr != NULL) {
// Use arr
free(arr); // Valid free
}
return 0;
}
Additional Tips
- Only free pointers returned by malloc, calloc, or realloc
- Don't modify pointers returned by memory allocation functions before freeing
- Keep track of which memory is dynamically allocated
- Use tools like Valgrind to detect invalid frees