Valgrind giving error but everything seems fine

时光怂恿深爱的人放手 提交于 2019-12-01 00:41:08

As Chris said valgrind tells you that you program is trying to write to memory that is outside of the allocated region:

Invalid write of size 4
   at 0x4027EB8: memcpy (mc_replace_strmem.c:635)
   by 0x4032269: do_opt (esp.c:113)
   by 0x804A51D: main (sendip.c:575)
 Address 0x41ceab0 is 144 bytes inside a block of size 146 alloc'd
   at 0x402699A: realloc (vg_replace_malloc.c:525)
   by 0x4032231: do_opt (esp.c:111)
   by 0x804A51D: main (sendip.c:575)

It tells you that in do_opt (in the file esp.c at line 111) you have called realloc to allocate 146 bytes of memory and now the function memcpy is trying to do a 4-byte write starting at 144 bytes from the start of that memory block, which will cause a write outside of the allocated region (144 + 4 > 146). It also tells you that memcpy was called from the do_opt function.

So either you are allocating to little memory or you are using wrong offset when copying to the memory. So next step would be to inspect the code in the locations reported by valgrind.

But what to do if the problem isn't obvious when looking at the code?

One option is to use valgrind's --db-attach option, which allows you to enter gdb. That will allow you to look around and check things like weather pack->alloc_len is the value you expect, and if &esp->tail.ivicv[priv->ivlen] points to the palace you expect it to compared to pack->data. (this could also be done the classic way by adding printf printing those values).

Below is my guess what the problem is, but hidden if you want to try to figure it out yourself first:

Maybe you are forgetting that ivicv is an uint32, and you have priv->ivlen measured in bytes. In that case changing it to &esp->tail.ivicv[priv->ivlen / sizeof(u_int32_t)] would help

==4331== Invalid write of size 4
==4331==    at 0x4027EB8: memcpy (mc_replace_strmem.c:635)
==4331==    by 0x4032269: do_opt (esp.c:113)
==4331==    by 0x804A51D: main (sendip.c:575)
==4331==  Address 0x41ceab0 is 144 bytes inside a block of size 146 alloc'd
==4331==    at 0x402699A: realloc (vg_replace_malloc.c:525)
==4331==    by 0x4032231: do_opt (esp.c:111)
==4331==    by 0x804A51D: main (sendip.c:575)
==4331== 

This is telling you that the memcpy call at line 113 is trying to write 4 bytes, but the address you gave it is 144 bytes into a block of 146 bytes, so its running off the end.

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