2014-02-26 32 views
-1

我的代碼編譯爲這樣,但我不明白爲什麼我一直得到這個錯誤告訴我,「調試斷言失敗」。爲什麼是這樣?調試斷言失敗(動態類型變量)

#include <iostream> 
using namespace std; 
struct Bag 
{ 
int k; 
}; 


int main() 
{ 
    int *p1; 
    int *p2; 
    char p3; 

    //k = 100; // Assigns variable of type bag to 100 

    p1 = new int; // Variables created using the new operator are called dynamic variables 
    p2 = new int; 


    *p1 = 30; 
    *p2 = 50; 
    p3 = 'K'; 

    *p1 = *p1 + *p2; 
    p1 = p2; 

    cout << "The sum of the two pointers is = " << *p1 << endl; 

    delete p1; 
    delete p2;    // Delete the dynamic variable p1 and return the memory occupied by p1 to the freestore to be reused. 

    system ("Pause"); 
    return 0; 
} 

回答

1

我猜你得到調試斷言失敗在該行:

delete p2; 

這裏的問題是,你設置「P1 = P2」,因此兩個指針指向的內存位置包含整數「50」。之後,您刪除指針p1,這意味着UN分配包含整數「50」的內存位置。

在這一點上,p2是未定義的,試圖刪除它將導致調試斷言失敗的錯誤。

+0

它也泄漏了原來由p2指向的內存。 –