分段故障在栈上分配大数组时 [英] Segmentation fault when allocating large arrays on the stack

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

问题描述

当我编译这个简单的C code是很好,但取消注释行之后它显示分段错误。我不知道什么是错。请帮助。

 #包括LT&;&stdio.h中GT;
诠释的main()
    {
    INT ARR [10002] [10002]
    INT颜色[10002]
    INT嘶鸣;
 // scanf函数(%d个,&安培;嘶);
    返回0;
    }


解决方案

您正在用吹堆栈改编颜色。 presumably当你调用 scanf函数被注释掉,编译器优化了所有这些变量了,但是当它是它试图在栈上分配内存present。

请变量全球,并在堆栈存储器VS堆内存读取的。

 #包括LT&;&stdio.h中GT;INT ARR [10002] [10002]
INT颜色[10002]诠释的main()
{
    INT嘶鸣;
    scanf函数(%d个,&安培;嘶);
    返回0;
}

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

解决方案

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天全站免登陆