Jack
Jack

Reputation: 271

Seg Fault with 2D array

I'm not sure why my 2d array initialization causes a seg fault, so I have

void viterbi_algorithm(double init[], double A[][26], double B[][2], int obs[], 
                       int mostLikelyStates[]){


   cout << "start" << endl;


   double table1[26][68000];
   double table2[26][68000];

..

If I comment out the two tables, everything will be okay. Am I asking for too much memories?

My error when I ran gdb

Program received signal SIGSEGV, Segmentation fault.
___chkstk_ms () at /usr/src/debug/gcc-4.8.1-3/libgcc/config/i386/cygwin.S:146
146             orq     $0x0, (%rcx)            /* probe there */

Upvotes: 1

Views: 1121

Answers (4)

Vlad from Moscow
Vlad from Moscow

Reputation: 311126

Define these arrays using keyword static

   static double table1[26][68000];
   static double table2[26][68000];

In this case they will be allocated in the static memory.

The other approach is to use standard container std::vector. For example

   std::vector<std::vector<double>> table1( 26, std::vector<double>( 68000 ) );
   std::vector<std::vector<double>> table2( 26, std::vector<double>( 68000 ) );

You also can define them with keyword static

   static std::vector<std::vector<double>> table1( 26, std::vector<double>( 68000 ) );
   static std::vector<std::vector<double>> table2( 26, std::vector<double>( 68000 ) );

Upvotes: 1

tenfour
tenfour

Reputation: 36906

You are simply running out of stack space. You are allocating sizeof(double)*2*26*68000 bytes on the stack. That's over 28mb, when stack space is typically around 2mb.

Instead, allocate the memory dynamically. There are several ways to do this. The simplest is:

std::unique_ptr<double[][68000]> table1(new double[26][68000]);
std::unique_ptr<double[][68000]> table2(new double[26][68000]);

table1[x][y] = 5.0;
....

Upvotes: 1

fredoverflow
fredoverflow

Reputation: 263350

That's way too much memory for the stack. You could allocate the arrays manually on the heap with new[] and delete[], but that's tedious and prone to errors. May I suggest a vector of arrays?

#include <vector>
#include <array>

std::vector<std::array<double, 68000>> table1(26);
std::vector<std::array<double, 68000>> table2(26);

Upvotes: 1

Sakthi Kumar
Sakthi Kumar

Reputation: 3045

double table1[26][68000];
double table2[26][68000];

would exceed the stack size of the program. Please allocate it dynamically.

Upvotes: 1

Related Questions