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
changes
sto 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
instead. This would copy the char array “abc” into
s. Note that this will cause a further bug –sis too short and doesn’t have space for the nul terminator at the end ofABC. Change you allocation to 4 bytes to fix thisor use
if
ABCis the max length you want to store.