glibc 检测到 free() 无效大小(快速)错误

glibc detected free() invalid size (fast) error?

本文关键字:快速 错误 无效 free 检测 glibc      更新时间:2023-10-16

当我执行以下函数时,我收到此错误,我不知道它是什么意思。这是函数:

void readf2()
{
    std::ifstream inFile("f2",std::ios_base::binary);
    std::string str(2, '');
    int i = 0;
    while(inFile.read(&str[i],2)){
    cout<<"Success: ["<< i << "] = "<< (int)str[i];                        ;
    cout<<"n";
    i++;
    }
}

该函数工作了一段时间,将各种数字写入控制台,然后随着此错误、回溯和内存映射而崩溃。发生这种情况是因为我要释放不存在的内存地址吗?

很可能你给read调用一个指向不属于你的内存的指针。

str[i] 返回字符串中的偏移量,但它不保证您有足够的内存来读取位置 (+2)。

您可能的意思是拥有一个int数组,并将i用作索引:

void readf2()
{
    std::ifstream inFile("f2",std::ios_base::binary);
    std::vector< int >  str; // if you're reading int's - use int, not string
    int i = 0;
    int j;
    while(inFile.read(&j,sizeof(int))){ // check what the content is here
    str.push_back(j);
    cout<<"Success: ["<< i << "] = "<< str[i];
    cout<<"n";
    i++;
    }
}