分段错误(核心转储)变量分配 [英] Segmentation fault(core dumped) variable assignment

查看:38
本文介绍了分段错误(核心转储)变量分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用 C++ 编写的程序,用 G++ 编译,在 Ubuntu 13.04 32 位上运行,出现以下错误:分段错误(核心转储)".

I have a program written in C++, compiled with G++, running in Ubuntu 13.04 32 bits, that is giving the following error: "Segmentation fault (core dumped)".

int main(int argc, char *argv[]){
printf("1\n");
int x = 0 , y = 0, count = 0;
printf("2\n");
char c;
printf("3\n");
int n_frames = (atoi(argv[1]) - 1);
printf("4\n");
int windowSize = WINDOW_SIZE; // WINDOW_SIZE is a define
printf("5\n");
// And the program go on....

long double frames[n_frames][377];

long double dis_frames[n_frames - (windowSize - 1)];
int tam_dis_frames = n_frames - (windowSize - 1);
long double white_top_hat[tam_dis_frames];

当n_frames"值(由 argv[1] 带来的值)较低时(测试到 300),错误不会发生,一切正常.

When the "n_frames" value (the one brought by argv[1]) is lower (tested until 300) the error does not happen and everything goes fine.

当该值较高时(如 1922),就会发生错误.当错误发生时,显示的最后一个 printf 是第四个,printf("4\n")".

When the value is higher (like 1922) the error happens. When the error happens the last printf that is shown is the fourth one, "printf("4\n")".

当值为 1853 或更低时,会显示printf("5\n")",但不会显示下一个 printf.

When the value is 1853 or lower the "printf("5\n")" is shown but the next printf wont show up.

有人知道什么可以解决吗?在程序如此简单的步骤中,分段错误(核心转储)的来源可能是什么....

Anyone has any idea what could solve it? What could be the source of Segmentation fault(core dumped) in a so simple step of the program....

推荐答案

您的 frames 数组是使用用户在命令行中传入的动态大小在堆栈上创建的.您已经超出了标准 C++ 领域,并使用了称为可变长度数组"的扩展/C99ism.

Your frames array is created on the stack using a dynamic size passed in by the user on the command line. You're already out of standard C++ territory here and using an extension/C99ism referred to as "Variable Length Arrays".

此外,您传入的 n_frames 值 (1922) 使帧数组的长度为 1922*377*10 字节,即大约 7.5 MB.在几乎所有标准台式机/笔记本电脑/操作系统上,您的堆栈大小限制大约为 1MB,因此您会以两种不同的方式被破坏.

Furthermore, the n_frames value you passed in (1922) makes the frames array 1922*377*10 bytes long, i.e. roughly 7.5 MB. On just about any standard desktop/laptop machine/OS, your stack size limit is roughly 1MB, so you're broken in two different ways.

问题的明显直接解决方案是像这样动态分配frames:

The obvious, direct solution to your problem is to dynamically allocate frames like so:

long double** frames = new (long double*)[n_frames];
for (int i = 0; i < n_frames; ++i) {
  frames[i] = new long double[377];
}

...当然不要忘记末尾相应的delete [].

...and of course don't forget the corresponding delete []'s at the end.

不过,话虽如此,您可能想了解 std::vector 作为 C++ 中事实上的动态分配数组类.

However, that said, you'll probably want to learn about std::vector as the de facto dynamically allocated array class in C++.

这篇关于分段错误(核心转储)变量分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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