【发布时间】:2021-10-28 03:51:34
【问题描述】:
我正在编写一个函数来按行主要顺序打印一个二维链表矩阵,并且我反复遇到我似乎无法解决的分段错误。这段代码有什么问题,尤其是在col = col->right 部分? (编辑:正如一些人所说,我也添加了代码的主要部分,希望它提供更多上下文)
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;
}
}};
这是它产生的错误:
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"
【问题讨论】:
-
@Vimal 应该是
while(row != NULL)或while(row != nullptr)。但两者都等价于while(row)。 -
我们不知道这些指针是否指向垃圾(未初始化)。测试
nullptr的指针并不意味着指针有效。如果mhead是垃圾值怎么办?请发帖minimal reproducible example。 -
代码看起来不错(除了使用原始指针)。构造
Node时,right成员是否可能未初始化为nullptr?由于这是您的停止条件,因此您需要确保链表的末尾(即您的列)正确终止。 -
对于指针的问题,你不能简单地在程序崩溃的地方拔出一段代码。崩溃的唯一原因是您的指针未指向有效内存。既然是这种情况,那么我们需要在整个上下文中查看程序,以了解这些指针在何处、何时以及如何初始化和使用。
-
mat[j]->right = mat[j+1];无效,因为那时你可能还没有初始化 ``mat[j+1]. Thusmat[j+1]` 包含一个不确定的值,并且使用这些值会导致到未定义的行为。
标签: c++ pointers matrix linked-list segmentation-fault