I'm writing a function to print a 2D linked-list matrix in row major order, and I'm repeatedly running into a segmentation fault that I can't seem to solve. What is wrong with this code, especially at the col = col->right
part? (Edit: Like a few have said, I've added the main part of the code as well, hopefully it provides more context)
struct Node
{ int data;
struct Node* right;
struct Node* down;
};
class Matrix{
Node* mhead = NULL;
public:
Node* newNode(int d){
Node* t = new Node;
t->data = d;
t->right = t->down = NULL;
return t;
}
void createMatrix(int m, int n){
Node *node, *mat[n];
int input;
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
cin>>input;
node = newNode(input);
if(i <= m-1)
node->down = mat[j];
mat[j] = node;
if(j <= n-1)
mat[j]->right = mat[j+1];
}
}
mhead = mat[0];
}
void printRowCol(){
Node *row = mhead;
while(row){
Node *col = row;
while(col){
cout<<col->data<<' ';
col = col->right;
}
cout<<"\n";
row = row->down;
}
}};
This is the error it produced:
Reading symbols from Solution...done.
[New LWP 868392]
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
Core was generated by `./Solution'.
Program terminated with signal SIGSEGV, Segmentation fault.
#0 Matrix::printRowCol (this=<synthetic pointer>) at Solution.cpp:85
85 cout<<col->data<<' ';
To enable execution of this file add
add-auto-load-safe-path /usr/local/lib64/libstdc++.so.6.0.25-gdb.py
line to your configuration file "//.gdbinit".
To completely disable this security protection add
set auto-load safe-path /
line to your configuration file "//.gdbinit".
For more information about this security protection see the
"Auto-loading safe path" section in the GDB manual. E.g., run from the shell:
info "(gdb)Auto-loading safe path"