C 不同的自由订单的双重误差

c++ double free error of different free order

本文关键字:误差 自由      更新时间:2023-10-16

我在测试C 时遇到了一个问题。当我运行第一个代码时,当第二个代码抛出"双免费错误"时,它会抛出。有人知道发生了什么事吗?

Test* test1 = new Test(1);
Test* test2 = new Test(2);
delete test1;
delete test2;
delete test1;
delete test2;

Test* test1 = new Test(1);
Test* test2 = new Test(2);
delete test1;
delete test1;
delete test2;
delete test2;

,要更好地了解程序的堆用法,您可以在gnu/linux上使用valgrind。当我在Valgrind下运行您的程序时,我会得到。请参阅摘要行

总用法:2个Allocs,4 Frees,8个字节分配

valgrind ./a.out 
==7594== Memcheck, a memory error detector
==7594== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==7594== Using Valgrind-3.10.0 and LibVEX; rerun with -h for copyright info
==7594== Command: ./a.out
==7594== 
==7594== Invalid free() / delete / delete[] / realloc()
==7594==    at 0x4C2A360: operator delete(void*) (vg_replace_malloc.c:507)
==7594==    by 0x40069E: main (in /home/ppm/algo/src/stackoverflow/a.out)
==7594==  Address 0x5a02040 is 0 bytes inside a block of size 4 free'd
==7594==    at 0x4C2A360: operator delete(void*) (vg_replace_malloc.c:507)
==7594==    by 0x400686: main (in /home/ppm/algo/src/stackoverflow/a.out)
==7594== 
==7594== Invalid free() / delete / delete[] / realloc()
==7594==    at 0x4C2A360: operator delete(void*) (vg_replace_malloc.c:507)
==7594==    by 0x4006AA: main (in /home/ppm/algo/src/stackoverflow/a.out)
==7594==  Address 0x5a02090 is 0 bytes inside a block of size 4 free'd
==7594==    at 0x4C2A360: operator delete(void*) (vg_replace_malloc.c:507)
==7594==    by 0x400692: main (in /home/ppm/algo/src/stackoverflow/a.out)
==7594== 
==7594== 
==7594== HEAP SUMMARY:
==7594==     in use at exit: 0 bytes in 0 blocks
==7594==   total heap usage: 2 allocs, 4 frees, 8 bytes allocated
==7594== 
==7594== All heap blocks were freed -- no leaks are possible
==7594== 
==7594== For counts of detected and suppressed errors, rerun with: -v
==7594== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)