gpt4 book ai didi

c++ - 尝试访问二维 vector 元素时出现段错误

转载 作者:行者123 更新时间:2023-11-28 06:54:13 26 4
gpt4 key购买 nike

我正在尝试使用 C++11 为集合关联缓存建模,但我的初始化或访问方法在某处出错了,或者我可能需要想出一个更好的数据结构来使用...

这是我的私有(private)变量声明:

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]

最佳答案

由于您在从 std::vector 读取时出现段错误,我几乎可以肯定您正在尝试读取超出其范围的地址(这意味着 addrOffset 太大) .如果您想确定,请尝试使用 cache.at(x).at(y) 而不是 operator[] - at()成员函数检查边界,它会抛出适当的异常。我建议您先检查此 vector 的大小,然后调整您的算法以将其考虑在内。

关于c++ - 尝试访问二维 vector 元素时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23378060/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com