简体   繁体   English

C ++分配段错误

[英]C++ allocation segfault

I have this code: 我有这个代码:

size_t count = new_data.size();
std::cout << "got the count: " << count << std::endl;
double g_x[count];
std::cout << "First array done\n";
double g_y[count];
std::cout << "Allocated array of size" << count << std::endl;

which gives me the output: 这给了我输出:

got the count: 1506538
Segmentation fault: 11

I honestly don't understand why. 老实说,我不明白为什么。 It work on another data set, but not on this one. 它适用于另一个数据集,但不适用于此数据集。

You're probably just getting a stack overflow here. 你可能只是在这里得到一个堆栈溢出。 Try to dynamically allocate the memory, ie use the heap. 尝试动态分配内存,即使用堆。

double* g_x = new double[count];
...
delete[] g_x;

Even better solution would be to use std::vector<> : 更好的解决方案是使用std::vector<>

#include <vector>

...

std::vector<double> g_x(count); // Creates vector with the specified size.

If you want a dynamically sized array, you either need to create it using new , or use one of the STL containers. 如果需要动态大小的数组,则需要使用new创建它,或使用其中一个STL容器。

Take a look at some of the answers at Static array vs. dynamic array in C++ 看一下静态数组与C ++中动态数组的一些答案

Your problem is that in C and C++ arrays are by definition defined at compile time so what you do is wrong and it's very strange that this code even compile (compiler should scream at you) 你的问题是在C和C ++数组中按照定义在编译时定义,所以你做的是错误的,这个代码甚至编译很奇怪(编译器应该尖叫你)

However if you need a runtime defined array you should either use std::vector or manually allocate memory (not reccomended if you don't have very specific needs) 但是,如果您需要一个运行时定义的数组,您应该使用std :: vector或手动分配内存(如果您没有非常具体的需求,则不会推荐)

PS you should check your compiler warning level and the verbosity because this code has serious flaws so it shouldn't even compile (it's also bad for you if you have a very low warning level etc because you could pick up some bad coding habits because you are using not knowingly compiler specific extensions to the language and this is going to drive you mad when changing environement) PS你应该检查你的编译器警告级别和详细程度,因为这个代码有严重的缺陷,所以它甚至不应该编译(如果你的警告级别很低等,这对你也有害,因为你可能因为你可能会遇到一些不良的编码习惯正在使用非语言编译器特定的语言扩展,这会在改变环境时让你发疯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM