在 C 中创建数组时出现分段错误 [英] Segmentation Fault on creating an array in C

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

问题描述

我最近迁移到了一台新笔记本电脑 - HP dv6119tx(Intel Core i5,4 GB RAM).它安装了 Windows 7 Home Premium 64 位.

I have recently migrated to a new laptop - HP dv6119tx (Intel Core i5, 4 GB RAM). It has Windows 7 Home Premium 64 bit installed.

我正在尝试在 C++(Dev C++)中创建一个长度为 10^6 的 int 类型的数组,我曾经在我的最后一台笔记本电脑(32 位 Windows 7 Ultimate/UbuntuLinux,2GB RAM)和我编写的所有其他环境(大约需要 3.5 MB RAM).但是使用当前设置,我在调试模式下收到分段错误"错误.

I am trying to create an array of type int of length 10^6 in C++ (Dev C++), which I used to create comfortably on my last laptop (32 bit Windows 7 Ultimate/Ubuntu Linux, 2GB RAM) and every other environment I have programmed on (It should take around 3.5 MB of RAM). But with the current setup, I am getting a "Segmentation Fault" error in Debug Mode.

屏幕截图(编辑):
第一个屏幕截图显示 10^5 在当前设置上工作,而 10^6 不在.我的最后一台机器上没有 10^6 的屏幕截图,但我已经用过很多次了.

SCREENSHOTS (EDIT) :
The first screenshot shows 10^5 working on the current setup and 10^6 not. I do not have a screenshot for 10^6 working on my last machine but I have used it many times.


如果我将数组声明为 global 或在堆上动态创建它为


The program would work just fine if I declared the array as global instead or created it dynamically on the heap as

int* a = new int[MAX];  

但我无法理解的是,当本地阵列在堆栈上占用微不足道的 3.5 MB 内存时(并且在 2 GB 机器上运行良好),为什么这个问题会出现在 4GB 机器上?这是用户堆栈空间问题吗?可以手动增加吗?

But what I fail to understand is that when the local array is taking a meager 3.5 MB of memory on the stack (and was working fine on a 2 GB machine), why should this issue surface with a 4GB machine? Is this a user stack space issue? Can it be increased manually?

编辑 2:
我特别问这个问题是因为我在 SPOJ 上提交了许多解决方案,在堆栈上创建了 10^6 大小的数组.以我目前的设置,我觉得无法做到这一点是残废的.我更喜欢堆栈而不是堆,因为它没有内存泄漏问题;和全局变量上的局部变量,因为它们很整洁并且不会弄乱命名空间.

EDIT 2:
I am particularly asking this question because I have submitted numerous solutions on SPOJ with 10^6 sized arrays created on the stack. With my current setup, I feel crippled not being able to do that. I prefer stack over heap whenever possible because it has no memory leak issues; and local variables over global variables because they are neat and do not mess up the namespace.

推荐答案

4 MB 的堆栈相当大.Windows 上的默认大小为 1MB.您需要使用链接器的 /STACK 选项来请求更大的尺寸.

A four megabyte stack is pretty big. The default size on Windows is 1MB. You need to use the /STACK option to the linker to ask for a larger size.

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

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