简体   繁体   中英

Where does this code segfault?

My question, now reduced to a - hopefully - minimal example, is why the following code segfaults.

It can of course be seen as a duplicate of the proposed question, provided you have found the latter. The problem is, I failed to find the question in my initial search and so may many newbies, not knowing the cause of error. I propose this as a duplicate I could have found:

Segmentation Fault before main

but the problem description is very long, so that I believe my minimised and much shorter code might be better for illustrating the problem. In any case, it is a duplicate. I propose the moderators set this as a duplicate and set a link from the second possible duplicate to the first one.

#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;        
}

A segfault does not occur when

#define N 3072

is replaced by

#define N 5

Neither does a segfault occur when the line

double a[LDA*N];

is omitted.

I am especially confused by the observation that the segfault occurs without reaching

printf( "-----------------------------------------------> Entry main.\n" );

which I put directly at the beginning of main.

For completeness, I run the code like this:

ludi@ludi-M17xR4:~/Desktop/tests$ g++ -o minicombo.x minicombo.cc && ./minicombo.x

The segfault is likely due to the array definition double a[LDA*N]; . This creates a 72MB array with automatic storage duration ("on the stack"). You have several alternatives.

  1. Use std::vector<double> created with the desired size or resize() member function.
  2. Dynamic allocation with std::unique_ptr<double[]> or new[]/delete[] . Beware, manual memory management is fraught with peril.
  3. Make the array static or global.

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