5

为什么当我这样做时:

char teststrcpy[5];

strcpy(teststrcpy,"thisisahugestring");

我在运行时收到此消息:

Abort trap: 6

它不应该只是覆盖teststrcpy内存右侧的内容吗?如果不是,Abort 陷阱是什么意思?

我在 MAC OSX 下使用 GCC 编译器

作为注释,并在回答一些评论时,我这样做是为了玩 C,我不会尝试在生产中这样做。别担心,伙计们!:)

谢谢

4

5 回答 5

2

在 C 语言中,没有人会告诉您“缓冲区太小”,如果您坚持将太多字符复制到太小的缓冲区,您将陷​​入未定义的行为恐惧

于 2013-01-22T19:28:29.067 回答
2

它不应该只是覆盖内存右侧的内容teststrcpy吗?

不一定,在分配的内存之外写入是未定义的行为。在您的情况下,某些东西检测到越界写入并中止了程序。

于 2013-01-22T19:26:27.353 回答
2

I don't own one, but I've read that Mac OS treats overflow differently, it won't allow you to overwrite memory incertian instances. strcpy() being one of them

On Linux machine, this code successfully overwrite next stack, but prevented on mac os (Abort trap) due to a stack canary.

You might be able to get around that with the gcc option -fno-stack-protector


Ok, since you're seeing an abort from __strcpy_chk that would mean it's specifically checking strcpy (and probably friends). So in theory you could do the following*:

char teststrcpy[5];
gets(teststrcpy);

Then enter your really long string and it should behave baddly as you wish.

*I am only advising gets in this specific instance in an attempt to get around the OS's protection mechanisms that are in place. Under NO other instances would I suggest anyone use the code. gets is not safe.

于 2013-01-22T19:32:09.410 回答
0

您的编译器很可能正在使用金丝雀来进行缓冲区溢出保护,因此,当发生溢出时会引发此异常,从而阻止您在缓冲区之外进行写入。

请参阅http://en.wikipedia.org/wiki/Buffer_overflow_protection#Canaries

于 2013-01-22T19:54:15.833 回答
0

如果您想覆盖 teststrcpy 的第 5 个字符之后的内容,那么您就是一个可怕的人。您可以将大小为 4 的字符串复制到您的 teststrcpy(第 5 个字符应保留为 NULL)。

于 2013-01-22T19:30:32.640 回答