1

I am trying to parse a .wav file header. If I remove the chunk_size +=... line, i get the expect result: RIFF, but once I add that line, I get RIFFÄÿÿÿ. Why is every value added to chunk_size apparently "appended" to chunk_id? How can chunk_id have more than four elements? Is there something basic about arrays or binary data that I don't understand? Is it inappropriate to use cout on a char array?

struct Wave
{
    Wave (FILE* file) {
        char header[44];
        uint size = fread(header, sizeof(char), 44, file);
        chunk_size = 0;
        for (uint i = 0; i < 4; i ++) {
            chunk_id[i] = header[i];
            chunk_size += header[i + 4] * pow(16, i);
        }
        cout << chunk_id;
    }
    char chunk_id[4];
    uint chunk_size;
    char format[4];
    ...
    ...
    ...
};
user1986358
  • 81
  • 2
  • 9

1 Answers1

2
cout << chunk_id;

works only when chunk_id is null terminated. Since it is not in your program, the program has undefined behavior.

Make chunk_id an array of 5 elements and make sure to null terminate it in the constructor.

Wave (FILE* file) {
    char header[44];
    uint size = fread(header, sizeof(char), 44, file);
    chunk_size = 0;
    for (uint i = 0; i < 4; i ++) {
        chunk_id[i] = header[i];
        chunk_size += header[i + 4] * pow(16, i);
    }
    chunk_id[4] = '\0';
    cout << chunk_id;
}
char chunk_id[5];
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • You should probably explain how to fix the issue, which should be pretty straightforward for this case. – Mooing Duck Mar 17 '16 at 20:54
  • So there isn't anything wrong with `chunk_id` itself, just with the way I'm attempting to view it? – user1986358 Mar 17 '16 at 20:57
  • Okay, I understand now. Thanks for your quick response and clear explanation. – user1986358 Mar 17 '16 at 21:01
  • Possible pitfalls include `chunk_id[i]` being `0`, or `'\n'`. (`cout` is a text stream). `cout.write(chunk_id, 4);` would have been another way (which does deal with the `0` issue but not the newline) – M.M Mar 17 '16 at 21:12