【发布时间】:2023-04-10 00:51:01
【问题描述】:
我正在尝试使用 C++11 对集合关联缓存进行建模,但是我的初始化或访问方法在某个地方出错了,或者我可能需要想出一个更好的数据结构来使用...
这是我的私有变量声明:
private:
int numSets; // Use this to control indexing
std::vector<std::vector<unsigned long long> >cache;
这是我的构造函数(玩弄调整大小/保留并初始化一堆值):
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);
}
GDB 输出:
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]
【问题讨论】:
-
嗯...你永远不会初始化
cache。至少在那些 sn-ps 中没有 -
@RedAlert 我在构造函数中所做的不是初始化它吗?我应该怎么做?
-
你应该从更简单的开始,比如
vector<int>。否则,您应该在发布问题之前将 back 简化为vector<int>。 -
您尝试初始化元素,而不是
cache本身。它开始时没有分配内存,而您只是开始尝试索引未分配给cache的内容。 -
如何分配缓存所需的内存?
标签: c++ caching vector segmentation-fault