c++stringc++11wavriff

Assigning an array with std::fgetc() return


I am trying to store the first 4 chars of a .awv file using the std::fgetc function

This is what I have

FILE* WAVF = fopen(FName, "rb");
std::vector<std::string> ID;
ID[4];
for (int i = 0; i < 4; i++)
{
    ID[i] = fgetc(WAVF);
}

I keep getting this error:

Exception thrown at 0x00007FF696431309 in ConsoleApplication3.exe: 
0xC0000005: Access violation writing location 0x0000000000000010.

Solution

  • Your program has undefined behavior!

    Your vector ID is empty. By calling operator[] on an empty std::vector, invoking an undefined behavior. You got lucky that your program got crashed, saying "Access violation".

    You need instead:

    // create a vector of string and initialize 4 empty strings
    std::vector<std::string> ID(4); 
    
    for (auto& element: ID)
    {
        element = some `std::string`s
    }
    

    However, in your case, std::fgetc returns intger as

    The obtained character on success or EOF on failure.

    So you might want the data structures such as std::vector<char> or (at best) std::string.