代码编译良好并运行良好,直到 for 循环遍历 f_read_Prediction_Set。段错误直接发生在该行之后……我错过了什么?
std::map< RAddr, uint32_t >* transCoherence::getCurrentSets(uint32_t log2AddrLs, uint32_t maskSets, uint32_t log2Assoc, int pid, RAddr caddr)//function to return prediction set
{
uint32_t set;
std::map< RAddr, uint32_t >* currentSets = new std::map< RAddr, uint32_t >;
std::map< RAddr, uint32_t >* f_read_Prediction_Set = new std::map< RAddr, uint32_t >;
for(std::map<RAddr, uint32_t>::iterator it = f_read_Prediction_Set->begin(); it!=f_read_Prediction_Set->end(); ++it)
{
set = (((it->first) >> log2AddrLs) & maskSets) << log2Assoc;
if(set == caddr)
(*currentSets)[set] = 1;
}
return currentSets;
}
最佳答案
让我把你的代码充满指针和动态分配,并将其转换为无错误和内存泄漏的版本:
std::map<RAddr, uint32_t> transCoherence::getCurrentSets(uint32_t log2AddrLs, uint32_t maskSets, uint32_t log2Assoc, int pid, RAddr caddr)
{
std::map<RAddr, uint32_t> currentSets;
std::map<RAddr, uint32_t> f_read_Prediction_Set;
// populate f_read_Prediction_Set
for (const auto& p : f_read_Prediction_Set) {
uint32_t set = (((p.first >> log2AddrLs) & maskSets) << log2Assoc);
if(set == caddr)
currentSets[set] = 1;
}
return currentSets;
}
这样你就可以完全忘记指针问题了。
如果您担心性能,您应该注意 C++ 中有一个叫做 RVO(返回值优化)的小东西,它可以避免在函数返回时实际复制 vector 。
此外,我一定会注意到您在 map 对象的名称中使用了“set”一词,因此知道有一个 std::set 对您有好处。如果您需要唯一的 key ,您可以使用该类。
关于c++ - for循环中指针的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22056654/