c++ - 使用指针时 C++ 中出现奇怪的分段错误
问题描述
我正在编写一个函数来按行主要顺序打印一个二维链表矩阵,并且我反复遇到我似乎无法解决的分段错误。这段代码有什么问题,尤其是在这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"
解决方案
问题中显示的代码可能是正确的。如果数据结构中的指针未正确初始化,即使正确,代码也可能崩溃。例如,如果最后一列的“右”元素保留为未初始化的垃圾而不是设置为空,则在下一次迭代期间,将从“垃圾”内存位置进行非法读取。
推荐阅读
- sql - 如何在一个结果列中写入不同的数据类型
- powershell - 有没有办法在两小时后停止 Azure 虚拟机?
- java - 使用Springframework Page对象时不将具有复合主键的实体的路径暴露给前端
- javascript - 将 ts sass 转换为 js 中的内联 css
- python - 将下拉值传递给 Django 中的 URL
- postgresql - 如何解决 CockroachDB 和 Spring-Boot 的密码问题
- reporting-services - 有没有办法全局更改 SSRS 上报表服务器上所有报表中的所有超链接?
- pdfmake - PDFMake 创建水平水印(非对角线)
- angular - Angular 6 matInput 样式不起作用
- tfs - 用户区域的 TFS Devops 自定义查询列表项