Search code examples
c++vectorfwrite

fwrite fails with invalid argument when writing a vector array


I'm having problems when trying to write a vector of structs to a file.

void Obj::Write(wchar_t const* filename)
{
    FILE* file;
    errno_t err = _wfopen_s(&file, filename, L"wb");
    assert (file && !err);

    assert (sizeof(VertexData_VNT) == 32);
    assert (vertexArray.size() == 1654);

    //unsigned int const vertexCount = vertexArray.size();
    //if (fwrite(&vertexCount, sizeof(unsigned int), 1, file) != 1) {
    //    perror ("fwrite(&vertexCount, ...) error:");
    //}

    if (fwrite(&vertexArray, sizeof(VertexData_VNT), vertexArray.size(), file) != vertexArray.size()) {
        perror ("fwrite(&vertexArray, ...) error:");
    }

    fclose(file);
}

where vertexArray is defined as:

std::vector<VertexData_VNT> vertexArray;

and VertexData_VNT is a 32 byte struct containing only floats.

Most of the time fwrite fails with a "Invalid argument" error, and writes nothing. Though sometimes it works fine... that doesn't make sense to me.

If I uncomment the lines above I instead get an "access violation reading location" exception at the same fwrite statement. It looks to be having problems with the memcpy in fwrite.c, line 139.

Anyone have any ideas?


Solution

  • Try &vertexArray[0] instead of &vertexArray

    std::vector allocates space dynamically. The data is not located where std::vector object is, but somewhere on the heap and the vector usualy only holds a few pointers.