简体   繁体   中英

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<> :

#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.

Take a look at some of the answers at Static array vs. dynamic array in 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)

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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