以下代码是否在数组[10] = 22或数组[9999] = 22处进行了?
我只想弄清楚整个代码是否会在它出错之前执行.(用C语言编写).
#include <stdio.h>
int main(){
int array[10];
int i;
for(i=0; i<9999; ++i){
array[i] = 22;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
Dan*_*und 13
这取决于...如果阵列后的记忆[9]是干净的,然后没有什么可能发生,直到ofcourse一个达到其被占用的内存段.
试试代码并添加:
printf("%d\n",i);
Run Code Online (Sandbox Code Playgroud)
在循环中你会看到它崩溃和烧伤的时候.我得到了各种结果,范围从596到2380.
使用调试器?
$ gcc -g seg.c -o so_segfault
$ gdb so_segfault
GNU gdb 6.8-debian
Copyright (C) 2008 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
and "show warranty" for details.
This GDB was configured as "i486-linux-gnu"...
(gdb) run
Starting program: /.../so_segfault
Program received signal SIGSEGV, Segmentation fault.
0x080483b1 in main () at seg.c:7
7 array[i] = 22;
(gdb) print i
$1 = 2406
(gdb)
Run Code Online (Sandbox Code Playgroud)
实际上,如果再次运行它,您将看到对于相同的i值,并不总是会发生段错误.可以肯定的是,当i> = 10时会发生这种情况,但是没有办法确定它将崩溃的i的值,因为这不是确定性的:它取决于内存的分配方式.如果内存是空闲的,直到数组[222](也就是没有其他程序使用它),它将一直持续到i = 222,但是对于i> = 10的任何其他值,它也可能崩溃.
答案可能是.C语言没有说明在这种情况下会发生什么.这是未定义的行为.编译器不需要检测问题,做任何事情来处理问题,终止程序或其他任何东西.所以它什么也没做.
你写的不是你的记忆,在实践中可能会发生以下三种情况之一:
写出界限:就是不要这样做.C语言在发生时不会告诉你什么,所以你必须自己关注它.