段错误当使用变量来启动阵列 [英] Segmentation Fault When Using Variable To Initiate Array

查看:111
本文介绍了段错误当使用变量来启动阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的第一个问题帖子很抱歉,如果我做作出任何失礼

This is my first question posting so sorry if I make make any faux pas'

用C

在我的节目,我创建一个全局变量的指针

In my program I create a global variable pointer

double *correlationData;

在主我创建这个局部变量:

In main I create this local variable:

int arrayLength = 0;

在主要我有一个内部的if语句for循环包含

in main I have an if statement inside a for loop which contains

arrayLength++;

在for循环我发起一个数组并把它分配给指针

after the for loop I initiate an array and assign it to the pointer

double correlationArray[arrayLength];
correlationData = correlationArray; 

但我得到一个段错误,在code的这一部分,我想不通为什么。如果我打印出arrayLength是1900000.首先我想也许这是太大的数组所以我尝试

but I get a "segmentation fault" at this part of the code and I can't figure out why. If I print out arrayLength it is 1900000. First I thought maybe this was too big for an array so I tried

correlationData = correlationArray[1900000];

和没有任何错误的工作。为什么我收到这个错误?

and that worked without any errors. Why I am getting this error?

推荐答案

这是由于计算器。您正在创建堆栈上一个巨大的数组。

This is due to a stackoverflow. You are creating a massive array on the stack.

190万双打是〜15 MB 。一个典型的堆栈是1 MB的顺序。

1900000 of doubles is ~15 MB. A typical stack is on the order of 1 MB.

你需要做的,而不是什么是使用动态分配它的malloc()

What you need to do instead is to allocate it dynamically using malloc().

在你的第二个测试案例:

In your second test case:

correlationData = correlationArray[1900000];

这不会使该数组。这只是一个野生数组访问(联合国)幸好没出事。

That doesn't make the array. It's just a wild array access that (un)luckily didn't crash.

这篇关于段错误当使用变量来启动阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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