我正在尝试用C ++ 11建模一个关联缓存,但我在初始化或访问方法的某个地方出错了,或者我需要提出一个更好的数据结构来使用...
以下是我的私有变量声明:
private:
int numSets; // Use this to control indexing
std::vector<std::vector<unsigned long long> >cache;
这是我的构造函数(使用resize / reserve和初始化值一堆):
SetAssociativeCache(int associativity) : numSets(512/associativity){
// Initialize the cache
for(int i = 0; i < numSets; i++){
for(int j = 0; j < (512/numSets); j++)
cache[i][j] = 0;
}
这是我在成员函数中访问它的地方:
unsigned long long line = cache[setIndex][addrOffset]; // Is this right?
在第一次访问时,setIndex设置为0,addrOffset设置为20.执行此行时,程序seg出现故障并崩溃。
有人能指出我在正确的方向吗?我假设它只是一个我没有看到的愚蠢的错误。
SetAssociativeCache(int associativity) : numSets(512/associativity) {
// Initialize the cache
for(int i = 0; i < numSets; i++){
std::vector<unsigned long long> temp;
cache.push_back(temp);
for(int j = 0; j < (512/numSets); j++)
cache[i].push_back(0);
}
151 unsigned long long line = cache[setIndex][addrOffset];
(gdb) s
std::vector<std::vector<unsigned long long, std::allocator<unsigned long long> >, std::allocator<std::vector<unsigned long long, std::allocator<unsigned long long> > > >::operator[] (this=0x28fec4, __n=0)
at c:/mingw/lib/gcc/mingw32/4.8.1/include/c++/bits/stl_vector.h:771
771 { return *(this->_M_impl._M_start + __n); }
(gdb) s
std::vector<unsigned long long, std::allocator<unsigned long long> >::operator[] (this=0x100, __n=20)
at c:/mingw/lib/gcc/mingw32/4.8.1/include/c++/bits/stl_vector.h:771
771 { return *(this->_M_impl._M_start + __n); }
(gdb)
Program received signal SIGSEGV, Segmentation fault.
0x00404d38 in std::vector<unsigned long long, std::allocator<unsigned long long> >::operator[] (this=0x100, __n=20)
at c:/mingw/lib/gcc/mingw32/4.8.1/include/c++/bits/stl_vector.h:771
771 { return *(this->_M_impl._M_start + __n); }
(gdb)
Program received signal SIGSEGV, Segmentation fault.
0x00404d38 in std::vector<unsigned long long, std::allocator<unsigned long long> >::operator[] (this=0x100, __n=20)
at c:/mingw/lib/gcc/mingw32/4.8.1/include/c++/bits/stl_vector.h:771
771 { return *(this->_M_impl._M_start + __n); }
(gdb)
[Inferior 1 (process 6096) exited with code 030000000005]
答案 0 :(得分:1)
由于从std::vector
读取时出现段错误,我几乎可以确定您正在尝试读取超出其范围的地址(这意味着addrOffset
太大)。如果您想确定,请尝试使用cache.at(x).at(y)
而不是operator[]
- at()
成员函数检查边界,它将抛出相应的异常。我建议您首先检查此向量的size
并调整算法以将其考虑在内。
答案 1 :(得分:0)
你需要做这样的事情:
for(int i = 0; i < numSets; i++){
std::vector<unsigned long long> temp;
cache.push_back(temp);
for(int j = 0; j < (512/numSets); j++)
cache[i].push_back(0);
}
否则,您永远不会为cache
分配内存。