分段故障(核心转储)C++错误,与指针有关

Segmentation Fault (core dumped) C++ error, pointer related

本文关键字:指针 错误 C++ 故障 核心 转储 分段      更新时间:2023-10-16

据我所知;我遇到的问题可能与指针有关。我对C++还比较陌生,虽然我认为我知道问题发生在哪里,但我很难理解为什么会发生。

下面是节点链表的构造函数,每个节点都存储一个字符串(称为"数据"),我希望有一个方法可以在链表上调用(在main中初始化),最终打印出每个节点的内容。我一开始只是试图打印第一个节点(由根指向)的内容,但后来遇到了分段错误。几个小时以来,我一直在摆弄我的代码,查找在线资源,但都无济于事。如有任何意见,我们将不胜感激。

#include <string>
#include <iostream>
#include "Node.h"
#include "Linked.h"

Linked::Linked(int size){
    Node *root;         //the start of the linked list, remains static
    root = new Node;   // sets it to point at a Node   
    Node *conductor;  // This will point to each node as it traverses the list
    conductor = root; // The conductor points to the first node
    if ( conductor != 0 ) {
        while ( conductor->next != 0)
        conductor = conductor->next;
    }
    for (int i = 0; i < size; i++){
        //std::cout << conductor->data;
        conductor->next = new Node;  // Creates a node at the end of the list
        conductor = conductor->next; // Points to that node
    }
}
void Linked::printMemory(){
int memorycheck[32] = { }; // 
Node *conductor; //creates a conductor
conductor = root; //sets conductor to point to the same Node that root does, the issue may occur here. Why?
for (int i = 0; i < 32; i++){
    std::cout << conductor->data; 

} 

这是我的链接头文件}

#ifndef LINKED
#define LINKED
#include <iostream>
#include <string>
#include "Node.h"

 class Linked {
 public:
     Node *root;
     Linked(int size);
     void addProgram (std::string name, int size);
     void printMemory ();

};
 #endif

我认为你的构造函数有问题。

Linked::Linked(int size){
    Node *root;         //the start of the linked list, remains static
    ...
}

在这里,您声明了一个变量root,而这与类定义中的root不同!请尝试从代码中删除此行。