Reputation: 2630
#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...
Upvotes: 1
Views: 175
Reputation: 1763
Problem is "printf("\n%s\n",buf++);" i.e. you are changing the base address returned by the "malloc" i.e. "buf". For "free();" api you have to pass the base address returned by the "malloc" api.
Alternative or Solution would be: Have an extra character pointer and temporarily store the base address returned by "malloc", if dynamic allocation is successful. Re-storing it back while freeing the allocated memory.
#include<stdio.h>
#include<stdlib.h>
int main()
{
static char* buf;
static char *temp;
buf = (char*)malloc(20*sizeof(char));
/* Better to check for the allocation failure */
if(!buf)
{
printf("Failed to allocate memory \n");
exit(EXIT_FAILURE);
}
else
{
temp = buf;
scanf("%s",buf);
while(*buf != '\0')
printf("\n%s\n",buf++);
/* restoring the base address back to buf */
buf = temp;
free(buf);
buf=NULL;
temp = NULL;
}
return 0;
}
Upvotes: 1
Reputation: 38228
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
.
Upvotes: 4