0
votes

I'm writing a C++ project with Visual Studio 12.0 in Windows 8.1.

Seemingly from nowhere, the following code:

int main()
{
    std::fstream file_out("test.dat", ios::out | ios::binary | ios::trunc);
    std::vector<bool> a(100, true);
    file_out.write((char*)&a[0], 100 * sizeof(bool));
    file_out.close();

    std::fstream file_in("test.dat", ios::in | ios::binary);
    std::vector<bool> b(100, false);
    file_in.read((char*)&b[0], 100 * sizeof(bool));
    file_in.close();

    return 0;
}

Is giving me the following run-time error:

Debug Assertion Failed!

Program: C:\Windows\SYSTEM32\MSVCP120D.dll
File: C:\Program Files (x86)\Microsoft Visual Studio
12.0\VC\include\xutility
Line: 201

Expression: ITERATOR LIST CORRUPTED!

But ONLY when run in debug mode; in release mode, it runs fine.

However, in debug mode, the following code does run fine (changed to an int vector, rather than a bool vector):

int main()
{
    std::fstream file_out("test.dat", ios::out | ios::binary | ios::trunc);
    std::vector<int> a(100, true);
    file_out.write((char*)&a[0], 100 * sizeof(int));
    file_out.close();

    std::fstream file_in("test.dat", ios::in | ios::binary);
    std::vector<int> b(100);
    file_in.read((char*)&b[0], 100 * sizeof(int));
    file_in.close();

    return 0;
}

What is causing this error?

1
Don't use C style casts. Use C++ casts. If you need a reinterpret_cast to get it to build, you probably have something wrong. The reason why in this case is because std::vector<bool> is broken in C++ and stores the data like a bitset and not an array of bool. - Neil Kirk

1 Answers

0
votes

Your code assumes that a std::vector<bool> a(100) creates a vector that holds a contiguous array equal to 100 * sizeof(bool) bytes in size. This is not correct.

Simply put, a std::vector<bool> is a specialized version of a vector. It isn't simply an array of bool that is wrapped in a class.

http://en.cppreference.com/w/cpp/container/vector_bool

Assuming your array size is always going to be constant, one solution is simply declare

bool a[100];

or

std::array a<bool, 100>

where indeed you have an array of 100 bool types.