C语言编程,为什么这大阵声明产生分段错误? [英] C programming, why does this large array declaration produce a segmentation fault?

查看:263
本文介绍了C语言编程,为什么这大阵声明产生分段错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这code数组声明中产生分段错误。我很困惑,为什么出现这种情况。我特意选择了20亿作为一种价值,因为它是低于2 ^ 31,并且可以融入一个整数变量。

  INT的main()
{    INT nums_size = 20亿;    INT NUMS [nums_size]    INT I;
    对于(i = 0; I< nums_size;我++){
        NUMS [我] =我;
    }
    返回0;}


解决方案

那么,对于一件事,那两家十亿整数。如果你有一个32位的地址空间和 INT 的大小为你的平台上四个字节(典型的32位平台),你不能存储很多整数周期。

即使如此,你只有堆栈,这就是自动变量位于提供给你这么大的空间。

如果你需要一个非常大阵,你应该dyncamically使用它分配的malloc()(如果你这样做,一定要释放它使用免费()当你用它做!)。

This code produces a segmentation fault during the array declaration. I'm confused as to why this happens. I intentionally selected 2000000000 as a value because it is below 2^31 and can fit into an integer variable.

int main()
{

    int  nums_size = 2000000000;

    int nums[nums_size];

    int i;
    for(i = 0; i < nums_size; i++) {
        nums[i] = i;
    }


    return 0;

}

解决方案

Well, for one thing, that's two billion integers. If you have a 32-bit address space and int has a size of four bytes on your platform (typical for a 32-bit platform), you can't store that many integers, period.

Even still, you only have so much space available to you on the stack, which is where automatic variables are located.

If you need a really large array, you should dyncamically allocate it using malloc() (and if you do so, be sure to free it using free() when you are done with it!).

这篇关于C语言编程,为什么这大阵声明产生分段错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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