Valgrind: invalid read of size 4 -> sigsegv, works fine without valgrind and in visual studio

I’ll explain the first error to you.

==1893== Invalid read of size 4
==1893==    at 0x80498E0: delete_min (huffman.c:331)
==1893==    by 0x80492DA: huffman_encode (huffman.c:196)
==1893==    by 0x8049DDE: encode_file (main.c:94)
==1893==    by 0x8049BBE: main (main.c:32)

At line 331, you’re probably reading an (unsigned) int, in a part of the memory you haven’t allocated for your own program.

==1893==  Address 0x441d9a8 is 0 bytes inside a block of size 452 free'd
==1893==    at 0x402BC70: realloc (in /usr/lib/valgrind/
==1893==    by 0x8049922: delete_min (huffman.c:335)
==1893==    by 0x80492CC: huffman_encode (huffman.c:195)
==1893==    by 0x8049DDE: encode_file (main.c:94)
==1893==    by 0x8049BBE: main (main.c:32)

This part gives more information about the part of memory you tried to read. It says you’ve already used the memory, but reallox freed it. That means you’re reading from an old pointer to a part of memory you’ve realloccated.

You should make sure you use the pointer realloc returns, and not the old one.

The reason this doesn’t crash when running outside valgrind, is that most of the time, the same part of memory will be allocated by realloc. So the pointer remains the same, and as such your code will work. However, sometimes, realloc will decide to move the part of the memory, and then your code will crash. Valgrind’s trying to warn you for this.

The rest of the errors will probably be solved when you’re using the returned pointer.

Leave a Comment