简体   繁体   中英

Attempting to parse a WAV file, memcpy results are unexpected

Assume that I have a small WAV file I've opened and dumped as a array of char for processing.

Right now, I am attempting to memcpy the fmt chunk ID into a 4 byte buffer.

char fmt[4];
memcpy(fmt_chunk_id, raw_file + 12, sizeof(char) * 4);

From my understanding of memcpy , this will copy the 4 bytes starting at offset 12 into fmt . However, when I go to debug the program I get some very strange output:

在此处输入图像描述

It seems to copy the fmt section correctly, but now for some reason I have a bunch of garbage after it. Interestingly, this garbage comes before format at offset bytes 0 ( RIFF ), and 8 ( WAVE ). It is a little endian file ( RIFF ).

I can't for the life of me figure out why I'm getting data from the beginning of the buffer at the end of this given that I only copied 4 bytes worth of data (which should exactly fit the first 4 characters f m t and space).

What is going on here? The output seems to indicate to me I'm somehow over-reading memory somewhere - but if that was the case I'd expect garbage rather than the previous offset's data.

EDIT:

If it matters, the data type of raw_file is const char* const .

The debugger is showing you an area of memory which has been dynamically allocated on the stack.

What is in all probability happening is that you read data from the file, and even if you asked to read, say, 50 bytes, the underlying system might have decided to read more (1024, 2048, or 4096 bytes usually). So those bytes passed around in memory, likely some on the stack, and that stack is being reused by your function now . If you asked to read more than those four bytes, then this is even more likely to happen.

Then the debugger sees that you are pointing to a string, but in C strings run until they get terminated by a zero (ASCIIZ). So what you're shown is the first four bytes and everything else that followed, up to the first 0x00 byte .

If that's important to you, just

char fmt[5];
fmt[4] = 0;
// read four bytes into fmt.

Now the debugger will only show you the first four bytes.

But now you see why you should always scrub and overwrite sensitive information from a memory area before free()ing it -- the data might remain there and even be reused or dumped by accident.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM