Search code examples
c++pointersfstream

C++ "pointer being freed was not allocated"


The code is simple and as follow:

#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();
}

It will have the output below:

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

The output is good, but it says that "pointer being freed was not allocated", however, I don't have the free() operation in my code, I wonder why this would happen?


However, r2 doesn't have the same problem with r3, The code as follow works well.

#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();
}

output:

4
123

Solution

  • You're causing undefined behavior when you write over the vector with:

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

    If you want a pointer to the array holding the vector data, you need to use r3.data(). And you can't use sizeof r3 to get its size, that's the size of the vector object, not the underlying array.

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

    See How to get std::vector pointer to the raw data?