#include <stdlib.h>
#include <stdio.h>
int main()
{
static char* buf;
buf = (char*)malloc(20*sizeof(char));
scanf("%s",buf);
while(buf[0] != NULL)
printf("\n%s\n",buf++);
free(buf);
buf=NULL;
system("pause");
return 0;
}
Message box during execution free(buf):
Windows has triggered a breakpoint in clean_rough_draft.exe.
This may be due to a corruption of the heap, which indicates a bug in clean_rough_draft.exe or any of the DLLs it has loaded.
This may also be due to the user pressing F12 while clean_rough_draft.exe has focus.
The output window may have more diagnostic information.
What's the reason? I just want to free memory without a leak...
Because you're incrementing buf
, and then trying to free()
it. By the time you free()
it, it is no longer pointing to what malloc()
returned.
Also (this isn't related to your crash), you probably should be checking buf[0] != '\0'
instead of buf[0] != NULL
.