大数组在 C 中给出分段错误 [英] Big array gives segmentation error in C

查看:23
本文介绍了大数组在 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天全站免登陆