Where is this segfault code?
My question, now boiling down to a hopefully minimal example, is the reason the following code segfaults.
Of course, this can be seen as a duplicate of the suggested question if you find it. The problem is that I was not able to find the question in my initial search, and so there may be many newbies without knowing the cause of the error. I suggest this as a duplicate that I could find:
Segmentation fault before main
but the description of the problem is very long, so I believe that my collapsed and shorter code might be better to illustrate the problem. This is a duplicate anyway. I suggest that the moderators set this as a duplicate and link from the second possible duplicate to the first.
#include <stdio.h>
/* Parameters */
#define N 3072
#define LDA N
/* Main program */
int main() {
printf( "-----------------------------------------------> Entry main.\n" );
/* Local arrays */
double a[LDA*N];
printf( "-----------------------------------------------> End main.\n" );
return 0;
}
Segfact does not arise if
#define N 3072
is replaced by
#define N 5
Also no segfault occurs when the line
double a[LDA*N];
omitted.
I am especially confused by the remark that the segfault happens without achieving
printf( "-----------------------------------------------> Entry main.\n" );
which I put directly at the beginning of the main one.
For completeness, I run the code like this:
ludi@ludi-M17xR4:~/Desktop/tests$ g++ -o minicombo.x minicombo.cc && ./minicombo.x
source to share
The likelihood of a segfault is probably due to the definition of the array double a[LDA*N];
. This creates a 72 MB array with automatic retention time ("on the stack"). You have several alternatives.
- Use
std::vector<double>
one created with the required size orresize()
member function. - Dynamic allocation using
std::unique_ptr<double[]>
ornew[]/delete[]
. Remember that manual memory management is dangerous. - Make an array
static
or global.
source to share