When I try to call free() function to free the memory, it isn't working properly. Here is my code:
unsigned char *indata;
unsigned char *outdata;
int file_func(const char *filename) {
//some other variables
for(i=0;i < no_of_files;i++) {
indata = malloc(sizeof(unsigned char));
outdata = malloc(sizeof(unsigned char));
//counts the number of characters from filename
numCharacters = readfile(filename, indata);
/* perform some operation on indata and get outdata(size is same as indata)*/
writefile(filename, outdata); //writes outdata to filename
free(indata);
free(outdata);
}
}
The above code does not work properly because free() is storing some random garbage value at indata & outdata(as they become dangling pointers). So I tried setting the pointers to null after freeing since I'm reusing the same pointers as:
free(indata);
indata = NULL;
free(outdata);
outdata = NULL;
Even then my code gets crashed as :
double free or corruption (out): 0x00000000025aa240 *
How can I overcome this problem or is there any other alternative to use dynamic sized pointers in a loop. Thank you.