Seg Fault Error C++, When Creating a 2d dynamic array -


i creating 2d dynamic array in order represent directed graph. set values false. data file set appropriate row/column combination true represent row has directed edge towards column. however, getting seg fault. wondering if me figure out how fix seg fault , appreciated. code below.

 #include <iostream> #include <fstream> #include <cstdio> #include <sstream> using namespace std;  class graph{     public:         string nodes;         bool **a;  };  int main(int argc, char** argv) {     if (argc != 2) {         cout << "no file given argument, , program end now." << endl;         return 0;    }      ifstream graph ( argv[1]);      graph mygraph;//graph object     string num;      int tempnum;     int tempnum2;     int tracker = 0;      while (graph.good())     {       graph >> num ;        if( tracker == 0) {// if first number create array             mygraph.nodes = num;              mygraph.a = new bool * [tempnum];             int i, m, n;             (i = 0; < tempnum; i++ ){                 mygraph.a[i] = new bool [tempnum];                         }              //set false             (m = 0; m < tempnum; m++) {                 for(n = 0; n < tempnum; n++){                     mygraph.a[n][m] = false; }}              tracker++;}//end of if tracker = 0      else {//otherwise make connection true in 2d array         if(tracker % 2 == 1){             stringstream convert(num);             int tempnum;             convert >> tempnum;             tracker++;             }         else if(tracker % 2 == 0) {          stringstream convert(num);         int tempnum2;         convert >> tempnum2;           mygraph.a[tempnum][tempnum2] = true;         tracker++;                 }         }      }//end of while     cout << mygraph.a[5][5] << "should false " << false << endl;     cout << mygraph.a[3][2] << "should false " << false << endl;     cout << mygraph.a[4][6] << "should false " << false << endl;     cout << mygraph.a[8][9] << "should true: " << true << endl;     cout << mygraph.a[7][5] << "should true: " << true << endl;     cout << mygraph.a[2][4] << "should true: " << true << endl; graph.close();  return 0;} 

you create new local tempnum variable in block:

    if(tracker % 2 == 1){         stringstream convert(num);         int tempnum;                  // <<<<<<<<<<<<         convert >> tempnum;         tracker++;         } 

it shadow 1 declared earlier:

int tempnum;                          // <<<<<<<<<<<< int tempnum2; int tracker = 0; 

therefore first index here undefined (the original variable again, has not been assigned ever):

    mygraph.a[tempnum][tempnum2] = true; 

that causes memory access violation , crash.


Comments

Popular posts from this blog

javascript - jquery or ashx not working -

opencv - DataType<cv::detail::deriv_type>::depth what is it used for -

python 3.x - Mapping specific letters onto a list of words -