【发布时间】:2020-12-07 22:08:00
【问题描述】:
我遇到了不知道如何解决的分段错误错误。 List.cpp 和 List.hpp 更大,但我只添加了我在 main.cpp 中使用的内容。代码如下:
列表.hpp
#ifndef LIST_H
#define LIST_H
#include <iostream>
#include <cstdlib>
struct Node{
int _value;
Node *_next;
};
struct List{
Node *_head;
int _size;
List();
void insert(int value);
void print();
};
#endif
列表.cpp
#include "List.hpp"
List::List(){
_size = 0;
_head = nullptr;
}
void List::insert(int value){
Node* node;
node->_value = value;
node->_next = _head;
_head = node;
}
void List::print(){
Node* head = _head;
if (_size > 0){
while(head){
std::cout << head->_value << " ";
head = head->_next;
}
std::cout<<std::endl;
}
else{
std::cout<<std::endl;
return;
}
}
main.cpp
#include <iostream>
#include "List.hpp"
int main(){
List *L = new List();
int N=0;
std::cout << "type the N value"<< std::endl;
std::cin >> N;
for(int i=0; i<=N; i++){
L->insert(i);
}
L->print();
delete L;
return 0;
}
控制台
▶ g++ -std=c++14 -Wall main.cpp List.cpp -o main && ./main out
List.cpp: In member function ‘void List::insert(int)’:
List.cpp:10:15: warning: ‘node’ is used uninitialized in this function [-Wuninitialized]
10 | node->_value = value;
| ~~~~~~~~~~~~~^~~~~~~
type the N value
3
[1] 13247 segmentation fault (core dumped) ./main out
我实际上也不知道如何调试它(我正在使用 VS Code),所以我不知道在堆栈和堆上创建的变量发生了什么。
【问题讨论】:
-
当您尝试访问无效的内存地址时会发生这种情况。也许您在使用它之前没有分配内存,或者您正在访问您的程序不允许访问的内存。
-
编译器正在告诉问题。
node是未初始化的指针。它指向什么?
标签: c++ class linked-list segmentation-fault singly-linked-list