Why does using char* and malloc together and using free result in mun_map chunk(): invalid pointer Aborted (core dumped)?

Viewed 15

I cannot post the complete code since its part of the pset solution. I did the following

char* buffer = malloc(sizeof(x+1));

Opened a file using fopen, read the data using fscanf, each word that i read using fscanf was less than x+1, then i freed the allocated memory using

free(buffer);

So far the code compiles and runs fine. However valgrid shows memory leak as i haven't closed the file. So i closed the opened file using fclose(file); When i close the file i get mun_map chunk(): invalid pointer Aborted (core dumped) error. This doesn't happen when i remove the fclose line.

The problem was solved when i used

char buffer[x + 1]; instead of char* buffer = malloc(sizeof(x+1));and removed free(buffer); from my program. I was also able to close the file using fclose and every thing works fine.

So why does using char* and malloc and freeing the memory result in that error and the char array doens't? I haven't changed anything in my new program except for using char buffer[] and removing free.

0 Answers
Related