【问题标题】:error with copy constructor and getter (mutator function)复制构造函数和 getter 错误(mutator 函数)
【发布时间】:2017-11-02 16:56:06
【问题描述】:

所以我创建了一个名为 WordFrequency 的类,它将一个字符串单词和一个 int 频率存储为私有成员变量。 一个 HashTable 函数,其中包含一个 WordFrequency** 、 hashsize 、 hashtable 中的 currentitems。

在使用复制构造函数时,我总是遇到错误 - 线程 1:EXC_BAD_ACCESS(代码=1,地址=0x0) 当在复制构造函数中调用时,它会将我重定向到 WordFrequency 类的 getter 函数。 我无法弄清楚为什么会这样。

复制构造函数。

Hashtable:: Hashtable(const Hashtable &hash){

    WordFrequency** temp = new WordFrequency* [hash.hashSize];
     this->arr = temp;
    for (int i = 0 ; i < hash.hashSize ; i++) {
        if (hash.arr[i] == NULL){  //pointer in hashstable is null
            continue;
        }
        //bucket is not empty
        if(this->search(this->arr[i]->getWord())   != 0  ){   //if same string already found in this hashtable
            this->arr[i]->increment();    // incrtement the frequency
            continue;
        }

        //else the string doest even exist in the hashtable.

        WordFrequency x ((hash.arr[i])->getWord());   //deep copying the word from the parameter hash
        temp[i] = &x;                               //pointing the hash table to the new the object

    }
    this->hashSize = hash.hashSize;
    this->currentItems = hash.currentItems;
}

词频类中的getter函数。

string WordFrequency:: getWord()  const {
    return this->word;
}

虽然getter函数看起来很简单,但不知道为什么会出现这个错误。

我还包括我的析构函数,这可能是问题所在。

Hashtable::  ~Hashtable() {
    for (int i = 0 ; i < this->hashSize ; i++){
        delete this->arr[i];
    }
   delete  [] this->arr;
    this->hashSize = 0;
    this->currentItems = 0;

}

输出运算符 -

ostream&  operator<< (ostream &out, const Hashtable &h){
    out << "Hashtable with  size - " << h.hashSize  << "and no of elements - " << h.currentItems << endl;

    for (int i = 0 ; i < h.hashSize ; i++){
        if (h.arr[i] == NULL){
            out << "0";
            continue;
        }
        else {
            out << ((h.arr[i])->getWord());   //bad access
        }
    }


    out << endl;
    return out;

}

【问题讨论】:

  • 使用 std::vector!
  • " 我总是收到一个错误 - 线程 1: EXC_BAD_ACCESS" 好的,我相信您的环境会让您运行调试器并查看确切的堆栈跟踪使用函数参数值导致该错误,以便您可以了解访问错误的原因。
  • 我认为分配需要使用自定义哈希表?如果没有,您可以使用std::mapstd::unordered_map 为自己省去很多麻烦。

标签: c++ class oop exc-bad-access copy-constructor


【解决方案1】:

在 HashTable 构造函数的 for 循环中,您存储的是堆栈分配对象的指针:

WordFrequency x ((hash.arr[i])->getWord());
temp[i] = &x; 

该内存在 for 循环范围之外被回收,这会在您稍后尝试访问该对象时导致“错误访问”。您应该改为新建对象:

temp[i] = new WordFrequency((hash.arr[i])->getWord()); 

【讨论】:

  • 现在我的输出运算符给了我一个错误的访问权限。你能看看吗。
  • 你的调试器究竟在哪一行代码告诉你错误正在发生?
  • @AryanArora 我注意到的一件事是,当您执行WordFrequency** temp = new WordFrequency* [hash.hashSize]; 时,您没有将指针初始化为 NULL。因此,当您执行if (hash.arr[i] == NULL){ //pointer in hashstable is null 时,新分配的数组中的指针未初始化。
猜你喜欢
  • 1970-01-01
  • 2013-10-13
  • 2020-07-02
  • 1970-01-01
  • 1970-01-01
  • 2023-04-01
  • 2013-07-30
  • 1970-01-01
  • 2017-08-18
相关资源
最近更新 更多