Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 690
Benedikt Bergenthal Avatar asked Apr 01 '26 22:04

Benedikt Bergenthal


1 Answers

You're probably just getting a stack overflow here. Try to dynamically allocate the memory, i.e. 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.
like image 90
Sergey Vyacheslavovich Brunov Avatar answered Apr 03 '26 14:04

Sergey Vyacheslavovich Brunov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!