大阵给用C分段错误 [英] Big array gives segmentation error in C

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

问题描述

我真的很新的C,所以我很抱歉,如果这是一个绝对的初学者的问题,但我得到一个分段错误,当我建立大阵,什么我做的是相关位:

I am really new to C, so I am sorry if this is a absolute beginner question, but I am getting a segmentation error when I am building large array, relevant bits of what I am doing is:

unsigned long long ust_limit;
unsigned long long arr_size;

/* ust_limit gets value around here ... */

arr_size = ((ust_limit + 1) / 2) - 1;
unsigned long long numbs[(int)arr_size];

这适用于ust_limit的一些价值,但是当它上面获得约4,000,000分割故障发生。我想是检测可能的段错误和正常失败。我怎么能知道哪些值会导致分段错误。而且,这是什么平台相关的?

This works for some values of ust_limit, but when it gets above approximately 4.000.000 a segmentation fault occurs. What I want is to detect a possible segfault and fail gracefully. How can I know which values would cause a segmentation fault. And, is this something platform dependant?

推荐答案

您最有可能得到一个堆栈溢出,因为你正在创建的堆栈上一个非常大的数组。为了避免这种情况,动态分配的存储器

You are most likely getting a stack overflow, since you are creating a very large array on the stack. To avoid this, allocate the memory dynamically:

unsigned long long *numbs = malloc(arr_size * sizeof(unsigned long long));

之后,当您使用数组后,再次释放它:

Later, when you are finished with the array, free it again:

free(numbs);

这篇关于大阵给用C分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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