插入unordered_set失败

时间:2018-10-15 10:11:23

标签: c++

首先,这是不是我自己的代码!它取自Google的Android源代码https://android.googlesource.com/platform/art/+/android-9.0.0_r10/tools/hiddenapi/hiddenapi.cc 因此,它应该经过测试并且应该起作用!但是,它在“插入...”时失败。 短代码:

/*...*/
std::unordered_set<std::string> light_greylist_;
/*...*/

/*Caller:*/ OpenApiFile(light_greylist_path_, &light_greylist_);

bool OpenApiFile(const std::string& path, std::unordered_set<std::string>* list) {

  std::ifstream api_file(path, std::ifstream::in);

  for (std::string line; std::getline(api_file, line);) {
/* line IS filled; I've checked it with a simple fprintf(): [this IS my code for testing]*/
    FILE *stream = fopen("test.txt", "a+");
    fprintf(stream, "%s\n", line.c_str());
    fclose(stream);

/* This is the point where it crashes with an "Illegal instruction (core dumped)"*/
    list->insert(line);
  }

  api_file.close();
  return true;
}

出了什么问题?

1 个答案:

答案 0 :(得分:0)

我将list用作引用而不是指针。很难说为什么原始代码使用指针,因为如果用NULL调用它很可能会崩溃。还要检查文件是否已成功打开(即使这次似乎已经成功打开了文件。)

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <unordered_set>

bool OpenApiFile(const std::string& path, std::unordered_set<std::string>& list) {

  std::ifstream api_file(path, std::ifstream::in);
  if (!api_file) {
    return false;
  }

  for (std::string line; std::getline(api_file, line);) {
    list.insert(line);
  }

  return true;
}

int main(int argc, char* argv[]) {
  std::vector<std::string> files(argv+1, argv+argc);

  for(auto& light_greylist_path_ : files) {
    std::unordered_set<std::string> light_greylist_;

    if (OpenApiFile(light_greylist_path_, light_greylist_) == false) {
      std::cerr << "failed opening "+light_greylist_path_+"\n";
    } else {
      for(auto& lg : light_greylist_) {
        std::cout << lg << "\n";
      }
    }
  }
  return 0;
}