超出 C 中的数组绑定 - 为什么这不会崩溃? [英] Exceeding array bound in C -- Why does this NOT crash?

查看:47
本文介绍了超出 C 中的数组绑定 - 为什么这不会崩溃?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码,它运行得很好,但我不知道为什么:

I have this piece of code, and it runs perfectly fine, and I don't why:

int main(){
   int len = 10;
   char arr[len];
   arr[150] = 'x';
}

说真的,试试吧!它有效(至少在我的机器上)!但是,如果我尝试更改太大的索引处的元素,例如索引 20,000,它就不起作用.所以编译器显然不够聪明,不能忽略那一行.

Seriously, try it! It works (at least on my machine)! It doesn't, however, work if I try to change elements at indices that are too large, for instance index 20,000. So the compiler apparently isn't smart enough to just ignore that one line.

这怎么可能呢?我真的很困惑...

So how is this possible? I'm really confused here...

好的,谢谢大家的回答!

Okay, thanks for all the answers!

所以我可以使用它来写入堆栈上其他变量消耗的内存,如下所示:

So I can use this to write into memory consumed by other variables on the stack, like so:

#include <stdio.h>
main(){
   char b[4] = "man";
   char a[10];
   a[10] = 'c';
   puts(b);
}

输出可以".这是一件非常糟糕的事情.

Outputs "can". That's a really bad thing to do.

好的,谢谢.

推荐答案

这怎么可能?

因为堆栈在您的机器上足够大,以至于堆栈上碰巧在 &arr[150] 所对应的位置有一个内存位置,并且因为您的小示例程序在任何 else 引用该位置之前退出,并且可能因为您覆盖了它而崩溃.

Because the stack was, on your machine, large enough that there happened to be a memory location on the stack at the location to which &arr[150] happened to correspond, and because your small example program exited before anything else referred to that location and perhaps crashed because you'd overwritten it.

您使用的编译器不会检查是否尝试越过数组的末尾(C99 规范说,在您的示例程序中,arr[150] 的结果会是未定义的",所以它可能无法编译它,但大多数 C 编译器不会).

The compiler you're using doesn't check for attempts to go past the end of the array (the C99 spec says that the result of arr[150], in your sample program, would be "undefined", so it could fail to compile it, but most C compilers don't).

这篇关于超出 C 中的数组绑定 - 为什么这不会崩溃?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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