在堆栈上分配大型数组时出现分段错误 [英] Segmentation fault when allocating large arrays on the stack

查看:19
本文介绍了在堆栈上分配大型数组时出现分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我编译这个简单的 C 代码时它很好,但是在取消注释后它显示分段错误.我不知道这有什么问题.请帮忙.

When I compiled this simple C code it's fine but after uncommenting the line it shows segmentation fault. I don't know what's wrong with this. Please help.

#include<stdio.h>
int main()
    {
    int arr[10002][10002];
    int color[10002];
    int neigh;
 // scanf("%d",&neigh);
    return 0;
    }

推荐答案

你用 arrcolor 搞砸了堆栈.大概当您对 scanf 的调用被注释掉时,编译器会优化所有这些变量,但是当它出现时,它会尝试在堆栈上分配内存.

You're blowing the stack with arr and color. Presumably when your call to scanf is commented out the compiler optimises all these variables away, but when it's present it attempts to allocate memory on the stack.

使变量成为全局变量,并读取堆栈内存和堆内存.

Make the variables global, and read up on stack memory vs heap memory.

#include<stdio.h>

int arr[10002][10002];
int color[10002];

int main()
{
    int neigh;
    scanf("%d",&neigh);
    return 0;
}

这篇关于在堆栈上分配大型数组时出现分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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