Why is Valgrind reporting "Invalid read 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 is valgrind

echo "Invalid read size 2"? I think it should be size 4.

Example post 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) 

      

+3


source to share


1 answer


I got "Invalid read size 2" while trying a malloc()

2x2 single channel texture (4 bytes / uint8_t

s). I assumed the allocation was too small - the word size in the architecture in question is 8 bytes (64-bit) - so I doubled the allocation and stopped complaining about valgrind. Since it malloc()

needs to be aligned, I was a little surprised by this (I'm sure it will be obvious to experts), but maybe it will help someone else. Doesn't have to use the extra allocated space, it just needs to be there.



... This is a fix, even if it doesn't make sense. The problem started on gcc 4.9.1 (Ubuntu 4.9.1-16ubuntu6).

+1


source







All Articles