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

旧城冷巷雨未停 提交于 2019-12-03 11:03:21

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/vgpreload_memcheck-x86-linux.so)
==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)
==1893==

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.

Based on your Valgrind errors, you are probably accessing and then freeing nodes you've already deleted. You should consider posting the Valgrind errors with the corresponding line numbers (compile with -g in gcc) to make it easier for us to help you.

Edit: The most glaring error, the segfault, is where you should start debugging. This line fails:

while((2*i)+2 < p_queue->grootte-1 && (queue[i]->amount > queue[(2*i)+1]->amount || queue[i]->amount > queue[(2*i)+2]->amount)){

presumably because queue is NULL. Why is it NULL? Probably because realloc didn't allocate anything. Why didn't it allocate anything? Either because you ran out of memory (unlikely) or because you tried to allocate something of size 0. (See http://www.cplusplus.com/reference/cstdlib/realloc/ for details of realloc). How could you request size 0? If p_queue->size-1 is 0.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!