2017-05-05 69 views
0

我在測試C++時遇到問題。 當我運行第一個代碼時,它會拋出錯誤,而第二個代碼拋出「double free error」。任何人都知道發生了什麼事?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;

+3

你調用*未定義行爲*,所以在技術上*無人*知道這是怎麼回事上;包括你的代碼。 – WhozCraig

+0

@WhozCraig我明白你的意思,但從技術上講,你可以反編譯程序,並檢查它在做什麼,只是爲了它。 –

+0

我知道這是未定義的行爲,但無論我運行多少次或使用什麼運行環境,結果都保持不變。未定義的行爲似乎有一些規律,這就是我很困惑。 @WhozCraig – yoke

回答

0

爲了更好地理解一個程序,你可以在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)