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

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

问题描述

此代码在数组声明期间产生分段错误.我很困惑为什么会发生这种情况.我特意选择了 2000000000 作为值,因为它低于 2^31 并且可以放入整数变量中.

int main(){int nums_size = 2000000000;int nums[nums_size];国际我;for(i = 0; i 

解决方案

嗯,一方面,那是 20 亿个整数.如果你有一个 32 位的地址空间,并且 int 在你的平台上有四个字节的大小(典型的 32 位平台),你不能存储那么多整数,句点.>

即便如此,您在堆栈上也只有这么多可用空间,这是自动变量所在的位置.

如果你需要一个非常大的数组,你应该使用 malloc() 动态分配它(如果你这样做,一定要使用 free() 释放它完成后!).

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