分段故障(核心转储)C++错误,与指针有关
Segmentation Fault (core dumped) C++ error, pointer related
据我所知;我遇到的问题可能与指针有关。我对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
不同!请尝试从代码中删除此行。
相关文章:
- 为什么我在空指针错误(链表)中获取成员访问权限
- std::函数指针错误:无法将 &A::a 转换为类型 std::function<>&&
- 为什么我得到 munmap_chunk():无效的指针:错误
- 成员模板函数指针错误
- 删除指针时,未分配被释放的 C++ 指针错误
- Visual Studio 中的"指向引用的指针"错误不会按发生位置的文件名显示
- C++数组指针错误无法将“int*”转换为“int**”
- C++ 通过函数指针错误调用成员函数
- 从 BST 中删除元素(指针错误)
- 随机生成的多维布尔指针错误
- 在测试中使用unique_ptr时指针错误无效
- 使用 malloc 而不是 new 会导致 free():指针错误无效
- 非标准语法;使用 '&' 创建指向成员的指针错误,将成员函数分配给向量时出错
- 抽象类和唯一指针 c++ 错误
- 返回函数指针错误而不带类型定义
- 练习中出现空指针错误
- 指针错误导致的分段错误(简单..)
- free():C++中的指针错误无效
- 使用布尔值数组"表达式必须具有指向对象类型的指针"错误C++
- 指针错误的C 数组