本文介绍了大数组在 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 中给出了分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 16:34