I have this code:
#define ABC "abc"
void main()
{
char *s = malloc(sizeof(char)*3);
printf("%p ", s);
s = ABC;
printf("%p ", s);
free(s);
}
This is the output:
0x8927008 0x8048574 Segmentation fault (core dumped)
As you can see, the address of string s changes after assignment (I think this is why free() gives segfault). Can anyone explain me why and how this happens? Thank you!
The line
s = ABC;
changes s to point to a different string which may well be in read-only memory. Attempting to free such memory results in undefined behaviour. A crash is likely.
I think you wanted
strcpy(s, ABC);
instead. This would copy the char array "abc" into s. Note that this will cause a further bug - s is too short and doesn't have space for the nul terminator at the end of ABC. Change you allocation to 4 bytes to fix this
char *s = malloc(4);
or use
char *s = malloc(sizeof(ABC));
if ABC is the max length you want to store.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With