【发布时间】:2012-11-22 11:26:12
【问题描述】:
我有这个代码:
#define ABC "abc"
void main()
{
char *s = malloc(sizeof(char)*3);
printf("%p ", s);
s = ABC;
printf("%p ", s);
free(s);
}
这是输出:
0x8927008 0x8048574 Segmentation fault (core dumped)
如您所见,字符串 s 的地址在赋值后发生了变化(我认为这就是 free() 给出 segfault 的原因)。 谁能解释我为什么以及如何发生这种情况? 谢谢!
【问题讨论】:
-
你丢失了 malloced 内存指针!!
-
请注意,C 中的
sizeof (char)始终为 1,因此在上述表达式中包含引用通常是毫无意义的。
标签: c string malloc constants free