Q:

free() collecting garbage value in c code and code doesn't work even when setting the pointer to NULL after freeing

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.

A:

You're only allocating 1 byte (sizeof(unsigned char)) for each of those variables. Either that's a mistake and you wanted to allocate sizeof(unsigned char) * some_number where some_number is dynamic, or you could just allocate on the stack:
unsigned char indata, outdata; // then use &indata and &outdata where you need a pointer

or
unsigned char indata[some_number];
unsigned char outdata[some_number];

or you can malloc once before the loop and free once after it.
The double free problem looks like one of the functions you're calling in the loop is calling free. Look carefully at readfile and writefile.

