简体   繁体   中英

Why does Valgrind report “Invalid read of size 2”?

struct item
{
    int a;
};
int main()
{
    item *a = (item *)malloc(sizeof(item));
    item *b = (item *)malloc(sizeof(item));
    short *c = (short *)b;
    c += 3; 
    memcpy(a, c, sizeof(int));
    free(a);
    free(b);
    return 0;
}

Why does valgrind echo "Invalid read of size 2"? I think it should be size 4.

Example message from Valgrind:

==19134== Invalid read of size 2
==19134== at 0x4C2F7E0: memcpy@@GLIBC_2.14 (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==19134== by 0x400625: main (main.cpp:19)
==19134== Address 0x51fd096 is 2 bytes after a block of size 4 alloc'd
==19134== at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==19134== by 0x4005FC: main (main.cpp:16) 

I got “Invalid read of size 2” trying to malloc() a 2x2 single channel texture (4 bytes / uint8_t s). I assumed the allocation was too small - word size on the architecture in question is 8 bytes (64-bit) - so I doubled the allocation and it stopped valgrind's complaints. Since malloc() is supposed to be aligned, I was a bit surprised by this (I'm sure it's something that would be obvious to the experts), but maybe it will help someone else. Not obliged to use the extra allocated space, it just needs to be there.

...It's a fix even if it doesn't bring insight. Problem occurred on gcc 4.9.1 (Ubuntu 4.9.1-16ubuntu6).

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