satyendra tiwari satyendra tiwari - 2 months ago 13x
C Question

Valgrind showing "invalid write of size 4 at fread" and memory leaks


function below tries to load contents of file pointed by pointer
and save its location at
and length in
. The code works fine but Valgrind shows the error of "invalid write at fread" and several memory leaks while using

Following is the code:

bool load(FILE* file, BYTE** content, size_t* length) {
// providing default values to content and length
*content = NULL;
*length = 0;

// initializing buffer to hold file data
int size = 512;
BYTE* buffer = NULL;
buffer = malloc(size);
if(buffer == NULL)
return false;

// bytes_read will store bytes read at a time
int bytes_read = 0;

// reading 512 bytes at a time and incrmenting writing location by 512
// reading stops if less than 512 bytes read
while((bytes_read = fread(buffer + size - 512 , 1, 512, file)) == 512)
//increasing the size of
size = size + 512;
if(realloc(buffer,size) == NULL)
return false;

// undoing final increment of 512 and increasing the size by bytes_read on last iteration
size = size - 512 + bytes_read;

// triming buffer to minimum size
if(size > 0)
BYTE* minimal_buffer = malloc(size + 1);
memcpy(minimal_buffer, buffer, size);
minimal_buffer[size] = '\0';
*content = minimal_buffer;
*length = size;
return true;

return false;


Your problem is here:

if(realloc(buffer,size) == NULL)

It reallocates the buffer, but you don't save the new pointer. The realloc function could allocate a new area of memory and copy the data there. It returns the new pointer.

An important note: Don't reassign back to the pointer you pass to the realloc function, use a temporary variable. Then if realloc fails you won't lose the original pointer and can clean up gracefully.