为什么我的程序在访问指针值时会返回垃圾?

0 c++ arrays pointers

当运行以下代码时,我得到垃圾输出.我已经调试了足够的数据,以便在我尝试访问时找出错误hobbies[i]->hobby.任何帮助,将不胜感激.我一直想弄清楚发生了几个小时的事情.

int Graph::addUserToHobby(std::string hobby, std::string id){
  int key = ((int)hobby[0] + (int)hobby[1])%HASHMAP_SIZE;
  int collisions = 0;
  while(hobbies[key] != NULL && hobbies[key]->hobby.compare(hobby) != 0 ){
    key++;
    collisions++;
    if(key >= HASHMAP_SIZE){
      key = 0;
    }
  }

  if(hobbies[key] == NULL){
    hobbylist hob;
    hob.hobby = hobby;
    hob.list.push_back(findVertex(id));
    hobbies[key] = &hob;
  }
  else{
    hobbies[key]->list.push_back(findVertex(id));
  }
  return collisions;

}

void Graph::displayHobbies(){

  for(int i=0; i<HASHMAP_SIZE; i++){
    if(hobbies[i] != NULL){
      cout << hobbies[i]->hobby << ": ";
      for(unsigned int j=0; j<hobbies[i]->list.size()-1; j++){
        cout << hobbies[i]->list[j]->name << ", ";
      }
      cout <<  hobbies[i]->list[hobbies[i]->list.size()-1]->name << endl;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

gsa*_*ras 9

将注意力集中在代码的那一部分:

if(hobbies[key] == NULL) {
  hobbylist hob;
  ...        
  hobbies[key] = &hob;
}
Run Code Online (Sandbox Code Playgroud)

hob超出范围时(在if语句的主体末尾),hobbies[key]将引用不再存在的内容.

稍后在您的程序中,正如您所注意到的那样,当您这样做时cout << hobbies[i]->hobby;,您将请求hobby超出范围的内容,这将调用未定义的行为(UB).


一些可能的解决方

  1. 使用an std::map代替现在使用的指针数组.容器将自动为您处理内存管理.(推荐的)
  2. 使用智能指针(例如std::unique_ptr),而不是原始指针.阅读更多内容 什么是智能指针,何时使用?
  3. 动态分配hob,以便延长其生命周期(这意味着当if语句的主体终止时,其hob生命周期不会终止).这种方法要求负责内存管理(您必须取消分配之前动态分配的每个内存(调用delete 您调用的次数new)).