I wrote the following program:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *s;
s = (char*)malloc(15);
s = "Hello World";
printf("%s",s);
free(s);
return 0;
}
There are no compilation errors. I'm getting this run time error: * Error in `./s': munmap_chunk(): invalid pointer: 0x0000000000400694 * Hello WorldAborted
Why am I getting this run time error and how can I fix it?
Is it because after the call to malloc
, s
received a certain address, and the assignment s = "Hello World"
modifies the address of s
, but then when doing free(s)
, the pointer that is sent to free
is not the one that was returned by malloc
?