我在测试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;

答案 0 :(得分:0)
为了更好地理解程序的堆使用情况,可以在Gnu / Linux上使用valgrind。当我在valgrind下运行你的程序时,我得到了这个。请参阅摘要行
总堆使用量:2个分配,4个释放,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)