2013-08-27 87 views
0

我的代碼包含兩個類。*** glibc detected *** ./parent_child_conscall:double free或corruption(fasttop):0x09d9e028 ***

class points{ 
      char *p; 
    public: points(){cout<<"constructor points called"<<endl;p=new char();} 
      virtual ~points(){cout<<"destructor points called"<<endl;delete(p);} 
    }; 
    class otherpoints: public points{ 
        points x1; 
    public: otherpoints(){cout<<"constructor otherpoints called"<<endl;x1=points();} 
      ~otherpoints(){cout<<"destructor otherpoints called"<<endl;} 
    }; 
    int main(int argc, char *argv[]) 
    { 
    otherpoints y1; 

    return 0; 
    } 

這裏我在基類構造函數中分配一個指針,並在相應的基類析構函數中銷燬指針的內存。

當我運行使用Valgrind的二進制文件,它提供了錯誤: -

constructor points called 

constructor points called 

constructor otherpoints called 

constructor points called 

destructor points called 

destructor otherpoints called 

destructor points called 

==2209== Invalid free()/delete/delete[] 

==2209== at 0x4024851: operator delete(void*) (vg_replace_malloc.c:387) 

==2209== by 0x8048A36: points::~points() (in home/santosh/programs/c++/parent_child_conscall) 

==2209== by 0x8048BB2: otherpoints::~otherpoints() (in /home/santosh/programs/c++/parent_child_conscall) 

==2209== by 0x804889A: main (in /home/santosh/programs/c++/parent_child_conscall) 

==2209== Address 0x42d5098 is 0 bytes inside a block of size 1 free'd 

==2209== at 0x4024851: operator delete(void*) (vg_replace_malloc.c:387) 

==2209== by 0x8048A36: points::~points() (in /home/santosh/programs/c++/parent_child_conscall) 

==2209== by 0x8048B32: otherpoints::otherpoints() (in /home/santosh/programs/c++/parent_child_conscall) 

==2209== by 0x8048889: main (in /home/santosh/programs/c++/parent_child_conscall) 

==2209== destructor points called 

==2209== 

==2209== HEAP SUMMARY: 

==2209==  in use at exit: 1 bytes in 1 blocks 

==2209== total heap usage: 3 allocs, 3 frees, 3 bytes allocated 

==2209== 

==2209== LEAK SUMMARY: 

==2209== definitely lost: 1 bytes in 1 blocks 

==2209== indirectly lost: 0 bytes in 0 blocks 

==2209==  possibly lost: 0 bytes in 0 blocks 

==2209== still reachable: 0 bytes in 0 blocks 

==2209==   suppressed: 0 bytes in 0 blocks 

==2209== Rerun with --leak-check=full to see details of leaked memory 

==2209== 

==2209== For counts of detected and suppressed errors, rerun with: -v 

==2209== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 18 from 7) 

無法知道哪1個字節的內存,我無法釋放。

我必須發佈回溯報告嗎?

任何幫助是感謝。

+1

閱讀關於[the three of](http://en.wikipedia.org/wiki/Rule_of_three_%28C%2B%2B_programming%29)。 –

+0

你需要賦予'points'一個賦值操作符和一個拷貝構造函數。查找*三條規則*。 – juanchopanza

回答

3

這裏的問題是您創建了points類的兩個實例。一個是points(),當然還有一個是x1

當你做x1 = points()創建與points()構建一個臨時的對象,這是再複製分配給x1,然後臨時對象被銷燬。由於您沒有提供複製賦值操作符,編譯器會爲您創建一個,但它只是複製指針,並且不分配新的內存。這意味着你有一段時間有兩個對象包含一個指向同一內存的指針。當臨時對象被銷燬時,釋放析構函數中的內存,將指針留在x1中。當x1被銷燬時,您嘗試刪除此懸掛指針,導致出現雙重錯誤。

解決這個問題的最好方法是實現一個複製賦值運算符,最好是一個複製構造函數,並在那些分配新內存和複製數據。

相關問題