Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 具有巨大局部变量的溢出堆栈?_C_Linux - Fatal编程技术网

C 具有巨大局部变量的溢出堆栈?

C 具有巨大局部变量的溢出堆栈?,c,linux,C,Linux,据说每个进程都有8MB的堆栈。 此堆栈将用于存储局部变量。 所以,如果我使用的数组的大小大于堆栈的最大值,它一定会溢出 int main() { int arr[88388608]; int arr1[88388608]; int arr2[88388608]; while(1); return 0; } 但我无法得到结果 欢迎来到优化编译器的世界 由于“仿佛”规则,编译器只需要构建与原始代码具有相同可观察结果的内容。 因此,编译器如果可以: 删除未使用的阵列 移除空循环 从堆栈外部的ma

据说每个进程都有8MB的堆栈。 此堆栈将用于存储局部变量。 所以,如果我使用的数组的大小大于堆栈的最大值,它一定会溢出

 int main()
{
int arr[88388608];
int arr1[88388608];
int arr2[88388608];
while(1);
return 0;
}

但我无法得到结果

欢迎来到优化编译器的世界

由于“仿佛”规则,编译器只需要构建与原始代码具有相同可观察结果的内容。 因此,编译器如果可以:

  • 删除未使用的阵列
  • 移除空循环
  • 从堆栈外部的main存储动态数组-因为main是一个特殊函数,环境只能调用一次
如果您想观察堆栈溢出(坏的,不是我们的好站点:-)), 你应该:

  • 使用一些代码填充数组
  • 在删除所有优化的情况下进行编译,最好是在调试模式下,告诉编译器尽可能准确地执行我编写的操作
当编译为
cc-gfoo.c-ofoo

#include <stdio.h>

#define SIZE 88388608

void fill(int *arr, size_t size, int val) {
    for (size_t i=0; i<size; i++) {
        arr[i] = val;
    }
}    
int main() {
    int arr[SIZE];
    int arr1[SIZE];
    int arr2[SIZE];

    fill(arr, SIZE, 0);
    fill(arr1, SIZE, 0);
    fill(arr2, SIZE, 0);
    printf("%d %d %d\n", arr[12], arr1[15], arr2[18]);

    return 0;
}
#包括
#定义大小88388608
填空(整数*arr,大小\u t大小,整数val){

对于(size_t i=0;i当堆栈溢出时,会出现未定义的行为,这有时可能会像预期的那样工作。此外,现在的编译器非常智能。既然这些数组未使用,为什么编译器实际上应该为它们创建空间?当您将arr的类型从
int
更改为
volatile int
时会发生什么?还有,AF好的,堆栈的大小在不同的系统上可能会有所不同。8MB也是一个很大的堆栈。我不指望有那么多。试着把
arr2[88388607]=0;
放在
while
循环中。@Lingxi:你的答案几乎是正确的。如果你把它翻译成C并取消删除它(并在注释中ping我)我将投赞成票,因为我的只是围绕你的解释