0
C++에서 지정된 연결 목록에 대한 딥 복사 생성자를 만들어야하는 할당 작업을하고 있습니다. 복사 생성자 내부 코드와 포인터는 잘 작동하지만, 인쇄 기능이 호출 될 때 라인 59의 기능에 세그먼트 오류를 얻을 :C++ 세그먼트 화 오류 메서드 호출시
cout << v->elem << " ";
나는 시간이 디버깅을하려고했는데 내가 가지고 seg 오류가 발생하는 이유는 알 수 없습니다. 할당에 대한 코드 (복사 생성자의 코드 만은 내 꺼야) :
#include <iostream>
#include <stddef.h>
#include "intSLinkedList.h"
using namespace std;
intSLinkedList::intSLinkedList(const intSLinkedList& other){
if(other.head == NULL){
this->head = NULL;
}
else{
intSNode* src_cursor = other.head;
while(src_cursor != NULL){
this->addFront(src_cursor->elem);
src_cursor = src_cursor->next;
}
}
}
intSLinkedList::intSLinkedList(): head(NULL), tail(NULL) { }
bool intSLinkedList::empty() const{ return head == NULL; }
const int& intSLinkedList::front() const{ return head->elem; }
//intSLinkedList::~intSLinkedList(){ while (!empty()) removeFront(); }
void intSLinkedList::addFront(const int& e) {// add to front of list
intSNode* v = new intSNode; // create new node
v->elem = e; // store data
v->next = head; // head now follows v
head = v; // v is now the head
if (head->next==NULL)
tail = head;
}
void intSLinkedList::addBack(const int& e) {// add to front of list
intSNode* v = new intSNode; // create new node
v->elem = e;
v->next = NULL; // store data
tail->next = v; // head now follows v
tail = v;
}
void intSLinkedList::removeFront() { // remove front item
intSNode* old = head; // save current head
head = old->next; // skip over old head
delete old; // delete the old head
}
void intSLinkedList::print() {
intSNode* v = head;
while (v != NULL){
cout << v->elem << " ";
v = v->next;
}
cout << endl;
}
int intSLinkedList::count() {
intSNode* v = head;
int n = 0;
while (v != NULL){
n++;
v = v->next;
}
return n;
}
헤더 파일 :
class intSLinkedList;
class intSNode {
private:
int elem;
intSNode* next;
friend class intSLinkedList;
};
class intSLinkedList {
public:
intSLinkedList();
intSLinkedList(const intSLinkedList& other);
bool empty() const;
const int& front() const;
//~intSLinkedList();
void addFront(const int& e);
void addBack(const int& e);
void removeFront();
void print();
int count();
private:
intSNode* head;
intSNode* tail;
};
및 테스터 파일 :
#include <iostream>
#include "intSLinkedList.h"
using namespace std;
int main(){
intSLinkedList int_sll;
int_sll.addFront(5);
int_sll.addFront(12);
int_sll.addFront(6);
cout << "int_sll : ";
int_sll.print();
intSLinkedList int_sll2 = int_sll;
cout << "int_sll2 : ";
int_sll2.print();
int_sll.addBack(100);
cout << "int_sll : ";
int_sll.print();
cout << "int_sll2 : ";
int_sll2.print();
}
내 GDB 출력 :
int_sll : 6 12 5
Program received signal SIGSEGV, Segmentation fault.
0x0000000000400cce in intSLinkedList::print (this=0x7fffffffe010)
at intSLinkedList.cpp:57
57 cout << v->elem << " ";
올바른 방향으로 포인트를 많이 주셔서 감사합니다.
디버거가 열려 있습니다. 오류를 일으키는 코드를 단계별로 실행하십시오. – tadman
'v'가 NULL 일 가능성이 큽니다. 꼬리가 nullptr 인 경우 – wallyk
addBack이 중단됩니다. –