【发布时间】:2016-02-24 08:11:11
【问题描述】:
#include<string.h>
int main()
{
char *s;
strcpy(s,"asdqw");
strcpy(s,s+2);
return 0;
}
这个程序在linux系统下运行没有报错,运行正常。 但是在 mac osx 中运行时,它显示 abort trap : 6。 为什么会这样?
【问题讨论】:
#include<string.h>
int main()
{
char *s;
strcpy(s,"asdqw");
strcpy(s,s+2);
return 0;
}
这个程序在linux系统下运行没有报错,运行正常。 但是在 mac osx 中运行时,它显示 abort trap : 6。 为什么会这样?
【问题讨论】:
你必须为s分配内存。像这样:
char *s = malloc(100);
否则,会导致未定义的行为。由于行为是未定义的,它在 Linux 上运行而不在 OS X 上运行都是合理的。
此外,正如@Florian Zwoch 明智地指出的那样,第二个strcpy() 对重叠的内存区域进行操作,这会再次调用未定义的行为。这是因为strcpy() 不允许内存区域重叠。您可能想要使用memmove(s, s + 2, sizeof (s + 2));,它允许目标和源重叠。
【讨论】:
malloc() 并不是这里唯一的问题。缺少malloc() 和使用strcpy() 都是错误的。
【讨论】: