首页 > 解决方案 > 使用指针时 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"

标签: c++pointersmatrixlinked-listsegmentation-fault

解决方案


问题中显示的代码可能是正确的。如果数据结构中的指针未正确初始化,即使正确,代码也可能崩溃。例如,如果最后一列的“右”元素保留为未初始化的垃圾而不是设置为空,则在下一次迭代期间,将从“垃圾”内存位置进行非法读取。


推荐阅读