C ++“指针被释放未被分配”

时间:2017-10-26 06:18:29

标签: c++ pointers fstream

代码很简单,如下:

#include <bitset>
#include <fstream>
#include <iostream>
#include <vector>

using namespace std;

int main() {
    vector<void*> v;

    int a1 = 4;
    string a2 = "123";
    vector<int> a3 = {1, 2, 3, 4};

    int s1 = sizeof a1;
    int s2 = sizeof a2;
    int s3 = sizeof a3;

    v.push_back((void*)(&a1));
    v.push_back((void*)(&a2));
    v.push_back((void*)(&a3));

    fstream _f("test.bin", ios::in | ios::out | ios::binary);
    _f.seekp(0);
    _f.write((char*)(v[0]), s1);
    _f.write((char*)(v[1]), s2);
    _f.write((char*)(v[2]), s3);

    int r1;
    string r2;
    vector<int> r3;

    _f.seekg(0);
    _f.read((char*)(&r1), s1);
    _f.read((char*)(&r2), s2);
    _f.read((char*)(&r3), s3);

    cout << r1 << endl
         << r2 << endl
         << r3[0] << " " << r3[1] << " " << r3[2] << " " << r3[3] << endl;
    _f.close();
}

它的输出如下:

4
123
1 2 3 4
test(51104,0x7fff9c57d3c0) malloc: *** error for object 0x7fe76fd00000:pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug

Command terminated

输出很好,但它说“没有分配指针”,但是,我的代码中没有free()操作,我想知道为什么会这样?

但是,r2与r3没有相同的问题,以下代码效果很好。

#include <bitset>
#include <fstream>
#include <iostream>
#include <vector>

using namespace std;

int main() {
    vector<void*> v;

    int a1 = 4;
    string a2 = "123";
    vector<int> a3 = {1, 2, 3, 4};

    int s1 = sizeof a1;
    int s2 = sizeof a2;
    int s3 = sizeof(int)*a3.size();

    v.push_back((void*)(&a1));
    v.push_back((void*)(&a2));
    v.push_back((void*)(&a3));

    fstream _f("test.bin", ios::in | ios::out | ios::binary);
    _f.seekp(0);
    _f.write((char*)(v[0]), s1);
    _f.write((char*)(v[1]), s2);

    int r1;
    string r2;
    vector<int> r3;

    _f.seekg(0);
    _f.read((char*)(&r1), s1);
    _f.read((char*)(&r2), s2);

    cout << r1 << endl
         << r2 << endl;
    _f.close();
    v.clear();
}

输出:

4
123

1 个答案:

答案 0 :(得分:1)

当您使用以下内容书写向量时,您会导致未定义的行为:

_f.read((char*)(&r3), s3);

如果需要指向包含矢量数据的数组的指针,则需要使用r3.data()。并且您无法使用sizeof r3来获取其大小,这是vector对象的大小,而不是基础数组。

int s3 = r3.size() * sizeof(int);
_f.read((char*)r3.data(), s3);

请参阅How to get std::vector pointer to the raw data?