Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Valgrind report "Invalid read of size 2"?

Tags:

c

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) 
like image 713
LTzycLT Avatar asked Oct 20 '22 23:10

LTzycLT


1 Answers

I got “Invalid read of size 2” trying to malloc() a 2x2 single channel texture (4 bytes / uint8_ts). 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).

like image 197
Engineer Avatar answered Oct 23 '22 01:10

Engineer