我想这崩溃,但它不会 [英] I want this to crash, but it doesn't

查看:142
本文介绍了我想这崩溃,但它不会的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

严重..
我是从80年代和一些空闲时间的老的黑客
在我的手上想我应该'C'大惊小怪什么

(我的背景是第四,它做的事情后到前
让我学到了很多有关强制错误的地段)

在这种情况下,我设置了一小阵,我
以为会到3号元素(0,1,2)

如果我执行编译,我还以为
我会得到一个彻头彻尾的越界错误,但NO-
它编译OK并运行甜蜜

在这一个不很匆忙,但它是
不利于小秃斑,所有scratchin。


  INT的main()
{
    炭构件[3] [16]; // 3个元素,每15字符长的加空    的printf(\\ n进入东西..);
    scanf函数(%S,会员[4]);    的printf(\\ n和别的东西。);
    scanf函数(%S,成员[5]);    的printf(%S,会员[4]);
    的printf(%S \\ n,成员[5]);    返回0;
}


解决方案

C没有做任何边界检查。 (第四也不行,所以我不知道那里的期望来的。)

充溢的数组的未定义行为的:它是允许的,但不是必需的,崩溃。在这种情况下,字节恰好是在相同的虚拟存储器页的堆栈帧,其中该局部变量被放置。如果框架是实现页面的结束时,CPU会承认一个错误的地址,并抱怨溢出。

如果你去了几个千字节或兆字节出来,你可能会看到像你期望的那样。

seriously.. I'm an old hacker from the 80's and with some spare time on my hands thought I'd 'C' what the fuss is about

( my background is Forth, which does things back to front so I learn a lot about forcing lots of errors )

In this case I've set up a small array which I thought would be 3 elements in size ( 0,1,2 )

If I run the compilation, I would have thought I'd have got an out-of-bounds error, but no- it compiles ok and runs sweetly

No great hurry on this one, but it's not good for the little bald spot, all that scratchin'.


int main()
{
    char members[3][16];  // 3 elements, each 15 char long plus null

    printf("\n enter something..  ");
    scanf( "%s", members[4]);

    printf("\n and something else..  ");
    scanf( "%s", members[5]);

    printf(" %s  ", members[4]);
    printf(" %s\n", members[5]);

    return 0;
}

解决方案

C doesn't do any bounds checking. (Forth doesn't either, so I'm not sure where the expectation came from.)

Overflowing an array is undefined behavior: it is allowed, but not required, to crash. In this case, the bytes just happen to be in the same virtual memory page as the stack frame where the local variable was placed. If the frame were towards the end of the page, the CPU would recognize a bad address and complain about the overflow.

If you go a few kilobytes or megabytes out, you will likely see something like you expect.

这篇关于我想这崩溃,但它不会的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆