【发布时间】:2013-01-06 18:10:18
【问题描述】:
考虑以下从文本文件中读取一行并对其进行标记的方法:
std::pair<int, int> METISParser::getHeader() {
// handle header line
int n; // number of nodes
int m; // number of edges
std::string line = "";
assert (this->graphFile);
if (std::getline(this->graphFile, line)) {
std::vector<node> tokens = parseLine(line);
n = tokens[0];
m = tokens[1];
return std::make_pair(n, m);
} else {
ERROR("getline not successful");
}
}
std::getline 发生崩溃(pointer being freed was not allocated - 此处不详述)。 如果我在其他系统上编译我的代码不会发生崩溃,并且很可能不是我自己的代码中的错误。目前我无法修复这个问题,我没有时间,所以我会在你的帮助下尝试绕过它:
您能否建议一个不使用std::getline 的替代实现?
编辑:我在 Mac OS X 10.8 上使用 gcc-4.7.2。我使用 gcc-4.7 在 SuSE Linux 12.2 上进行了尝试,没有发生崩溃。
编辑:一种猜测是parseLine 破坏了字符串。这是完整性的代码:
static std::vector<node> parseLine(std::string line) {
std::stringstream stream(line);
std::string token;
char delim = ' ';
std::vector<node> adjacencies;
// split string and push adjacent nodes
while (std::getline(stream, token, delim)) {
node v = atoi(token.c_str());
adjacencies.push_back(v);
}
return adjacencies;
}
【问题讨论】:
-
“并且很可能不是我自己的代码中的错误” - 我可以争论这个,但由于你没有时间,我不会。
-
如果释放的原因是字符串,那么问题很可能是字符串 (
line),而不是std::getline。替换std::getline可能无济于事。我最好的猜测是parseLine()破坏了字符串。 -
@cls - 很可能,你在某处有 UB。
-
@cls 原因可能是代码中某处调用的未定义行为,而您没有显示
-
调试版本中未在发布版本中显示的故障转储几乎是始终为您的提供的调试检查保护试图警告你有问题。忽略这一点是通过仅与 release-libs 链接来“解决”汽车刹车损坏的问题,只需驶向可以反弹的东西,希望损坏最小。