1

나는 이러한 변수를 가지고 :C++ 복사 생성자/할당 연산자 오류

char** wordList_; 
int wordListCapacity_; 
int* wordCountList_; 
char* fileName_; 
int nUniqueWords_; 
int nTotalWords_; 
int nTotalCharacters_; 

내 복사 생성자 :

FileIndex::FileIndex(const FileIndex& fi) 
{ 
    fileName_ = new char[strlen(fi.fileName_) + 1]; 
    strcpy(fileName_, fi.fileName_); 
    cout << "Jiasd?" << endl; 
    wordListCapacity_ = fi.wordListCapacity_; 
    nUniqueWords_ = fi.nUniqueWords_; 
    nTotalWords_ = fi.nTotalWords_; 
    nTotalCharacters_ = fi.nTotalCharacters_; 

    wordList_ = new char*[wordListCapacity_]; 
    wordCountList_ = new int[wordListCapacity_]; 
    for(int i = 0; i < nUniqueWords_; i++) { 
     wordList_[i] = fi.wordList_[i]; 
     wordCountList_[i] = fi.wordCountList_[i]; 
    } 
} 

내 과부하 할당 연산자 : 나는의 FileIndex을 만들 때마다

FileIndex& FileIndex::operator=(const FileIndex& fi) 
{ 
    fileName_ = new char[strlen(fi.fileName_) + 1]; 
    strcpy(fileName_, fi.fileName_); 
    wordListCapacity_ = fi.wordListCapacity_; 
    nUniqueWords_ = fi.nUniqueWords_; 
    nTotalWords_ = fi.nUniqueWords_; 
    nTotalCharacters_ = fi.nTotalCharacters_; 
    wordList_ = new char*[wordListCapacity_]; 
    wordCountList_ = new int[wordListCapacity_]; 
    for (int i = 0; i < nUniqueWords_; i++) { 
     wordList_[i] = new char[strlen(fi.wordList_[i])+1]; 
     strcpy(wordList_[i], fi.wordList_[i]); 
     wordCountList_[i] = fi.wordCountList_[i]; 
    } 
    return *this; 
} 

(FirstIndex) 초기화하고 무언가를 사용하여 멤버 변수를 초기화하십시오. gful (하지 NULL) 나는 복사 생성자와 대입 연산자 테스트하는이 라인이 있습니다

FileIndex secondIndex = firstIndex; 
FileIndex thirdIndex; 
secondIndex = thirdIndex; // Segmentation fault here 

나는 할당 연산자와 세그먼트 오류를 ​​얻을 수를하지만 난 그것 때문에 복사 생성자의 결함 코드의 수 있습니다 느낌이있다 . 즉, 복사 생성자에 오류가있는 경우 대입 연산자에도 오류가있을 수 있습니다.

미리 도움을 청하십시오!

+0

수업을 단순화하면 어떻게됩니까? – Beta

+0

소멸자는 어떻게 생겼습니까? –

+0

대신'std :: vector'를 사용하면 문제가 해결 될 것입니다. * ctor-initializer * 목록에 대해서도 배워보십시오. –

답변

1

복사 생성자를 확인하십시오.

for(int i = 0; i < nUniqueWords_; i++) { 
    wordList_[i] = fi.wordList_[i]; 
    wordCountList_[i] = fi.wordCountList_[i]; 
} 

문제는 wordList_[i] = fi.wordList_[i];입니다. 당신은 할당 연산자에서하는 것처럼 새로운 메모리를 할당하고 strcpy를 수행하지 않습니다. 대신 새 사본은 실제로 복사중인 인스턴스의 데이터를 가리 킵니다. 데이빗 슈 와츠가 언급 한 내용 일 수도 있습니다.

2

나는 당신이 당신의 클래스 std::stringstd::vector<T>을 사용하려는 생각합니다. 또한 무엇이 잘못되었는지를 확인하기 위해 기본 생성자와 소멸자를 확인해야합니다. 예를 들어, 귀하의 설정에 따라 기본 생성자에서 일부 멤버를 초기화하지 않았습니다. 또한 할당 연산자에는 여러 리소스 누수가 있으며 자체 할당을 시도하면 상당히 나 빠질 수 있습니다.

T& T::operator= (T other) { 
    other.swap(*this); 
    return *this; 
} 

이것은 복사 생성자에 대해 수행 된 작업을 활용하고 일반적으로 아주 쉽게 할 수있는 swap() 멤버를 사용 : 일반적으로,이 같은 할당 연산자를 구현하는 것이 좋습니다 것입니다. 당신이 (당신이 기본 ctor에 표시되지 않기 때문에 얘기하기 어렵다) 제대로 wordListCapacity_를 초기화 할 수있는 것처럼

0

것 같습니다. int이므로 음수 값을 가질 수 있으며 wordList_ = new char*[wordListCapacity_];을 시도하면 segfault가 발생할 수 있습니다. 다른 문제가있을 수 있습니다.