I have a very simple program that malloc()'s some data, initializes it, then frees it and I keep getting this error. I have no idea why this is happening, any ideas?
#include <stdlib.h>
#include <stdio.h>
int main(){
int * big_mem;
int row_size = 4096; //not sure about this....
int num_rows = 5;
int const_val = 0xFFFFFFFF;
big_mem = (int *) malloc(row_size * num_rows);
if(!big_mem){
printf("Failed to malloc, exiting...");
return 0;
}
i = 0;
for(; i < row_size * num_rows; ++i){
big_mem[i] = const_val;
}
printf("Initialized mem, ");
free(big_mem);
big_mem = NULL;
return 0;
}
Output:
*** Error in `./test': free(): invalid next size (fast): 0x0000000000819010 ***
Use malloc(row_size * num_rows * sizeof(int))
.
You didn't malloc enough memory so your loop wrote past your malloc()ed memory. I'm surprised you didn't just get a segmentation fault.