-3
나는 STL 콘테이너를 사용하는 것을 허용하지 않는다!C++에서 템플릿 오버로드 된 연산자를 호출 할 때 세그먼트 화 오류가 발생하는 이유는 무엇입니까?
다음 코드에서는 SortedListClass(const SortedListClass<T> &rhs)
, operator=(const SortedListClass<T> &rhs)
및 clear()
함수에서 세그먼트 오류가 발생합니다.
이
디버거로부터의 결과이다 :#0 __GI___libc_free (mem=0x4) at malloc.c:2929 #1 0x00000000004016d6 in SortedListClass::clear (this=0x7ffffffde470) at SortedListClass.inl:45 #2 0x00000000004011b5 in SortedListClass::operator= (this=0x7ffffffde470, rhs=...) at SortedListClass.inl:28 #3 0x0000000000400c88 in main() at project5.cpp:33
SortedListClass.inl
라인 45 다음 delete tempHead;
SortedListClass.inl
라인 28 다음 this->clear();
project5.cpp
라인 (33)은 다음과 같다 : copyTestList = testList;
다음은 코드입니다. :
SortedListClass.inl
template<class T>
SortedListClass<T>::SortedListClass()
{
head = NULL;
tail = NULL;
cout<<"Empty list intialized...."<<endl;
}
template<class T>
SortedListClass<T>::SortedListClass(const SortedListClass<T> &rhs)
{
cout<<"Copied Value(s)"<<endl;
LinkedNodeClass<T> *rhsFront;
LinkedNodeClass<T> *newCopyNode;
rhsFront = rhs.head;
while(rhsFront != NULL)
{
newCopyNode = new LinkedNodeClass<T>(rhsFront,rhsFront->getValue(),
rhsFront->getNext());
rhsFront = newCopyNode;
rhsFront = rhsFront->getNext();
}
}
template<class T>
void SortedListClass<T>::operator=(const SortedListClass<T> &rhs)
{
this->clear();
*this = SortedListClass(rhs);
}
template<class T>
void SortedListClass<T>::clear()
{
LinkedNodeClass<T>*tempHead;
LinkedNodeClass<T>*tempTail;
tempHead = head;
tempTail = tail;
while(tempHead != NULL || tempTail != NULL)
{
cout << "Deleting node(s) --> "<< endl;
tempHead = head;
delete tempHead;
tempHead = NULL;
head = tempHead;
tempTail = tail;
delete tempTail;
tempTail = NULL;
tail = tempTail;
}
cout<<"Deleting complete"<<endl;
}
project5.cpp
int main()
{
SortedListClass<int>testList;
testList.insertValue(3);
testList.printForward();
testList.insertValue(4);
testList.printForward();
int theVal = 0;
SortedListClass<int>copyTestList(testList);
copyTestList = testList;
copyTestList.getNumElems();
int index = 0;
int outval = 0;
copyTestList.getElemAtIndex(index,outval);
copyTestList.printForward();
copyTestList.removeLast(theVal);
copyTestList.printBackward();
return 0 ;
}
표시 된 코드는 [mcve]에 대한 stackoverflow.com의 요구 사항을, 그래서 권위있는 대답은 할 수 없습니다 이행하지; 그래서 일반적인 대답은 "세분화 오류가 당신의 코드 어딘가에있는 버그 때문에"적용될 것입니다. 그래도 기본 생성자는 'head'및 'tail'이라는 클래스 멤버를 초기화하는 것으로 보이며 복사 생성자에서 찾을 수 없습니다. 그럴 가능성이 매우 높습니다. 그런 다음 clear()에서 : 'tempHead = NULL; 머리 = tempHead;'도 꽤 틀린 것 같다. 여기서 명백하고 근본적인 문제가 너무 많습니다. –
'clear' 함수는 전혀 이해가되지 않습니다. 'while' 루프의 첫 번째 반복이 끝날 때'head'와'tail'은 모두'NULL'으로 설정됩니다. 그러면 어떻게 반복 될 수 있습니까? Sam의 코멘트에 동의합니다. "* 여기에 명백하고 근본적인 문제가 너무 많습니다. *"버그를 모두 찾아서 고쳐야 만합니다. 아마도이 프로젝트가 당신의 기술 수준에 너무 야심적 일 수 있습니다. –
'head'와'tail' 멤버를 초기화하지 않는 복사 생성자와'while()'루프가 모두 잘못되었습니다. 그리고'operator ='는 끝없이 재귀 루프가 생기는 것처럼 보입니다. –