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

问题描述

我有这块code,而且它运行完全正常,而且我不为什么:

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';
}

说真的,试试吧!它的工作原理(至少在我的机器上)!
这不,但是,工作,如果我试图改变在那个太大,比如指数20000元素的索引。所以编译器显然是不够聪明,只是忽略一行。

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.

好吧,谢谢。

推荐答案

C编译器一般不会产生code,检查数组边界,为求效率。超出界限数组访问导致未定义的行为,一
可能的结果是,它的工作原理。它不能保证导致崩溃或其他
诊断,但如果你的操作系统虚拟内存的支持,您的数组索引指向虚拟内存的位置,这还没有映射到物理内存,你的程序更有可能崩溃。

C compilers generally do not generate code to check array bounds, for the sake of efficiency. Out-of-bounds array accesses result in "undefined behavior", and onepossible outcome is that "it works". It's not guaranteed to cause a crash or otherdiagnostic, but if you're on an operating system with virtual memory support, and your array index points to a virtual memory location that hasn't yet been mapped to physical memory, your program is more likely to crash.

这篇关于超过数组用C联系在一起 - 这为什么不会崩溃?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 04:08