0

我被給出以下解釋的問題: 「僅使用變量q,爲結構點內的整型指針動態分配內存」。我寫了下面的代碼,但是,我無法刪除動態分配的整數,因爲它給我一個運行時錯誤,說我正在刪除一些不存在的東西。我在分配後檢查了內存地址 ((* q) - > x - > x)和srcX,並且它們具有相同的地址。我怎樣才能釋放這個動態分配的整數?在另一個結構中釋放指針內的指針

#include <iostream> 

using namespace std; 

struct point { 
    int *x; 
    int *y; 
}; 

struct line { 
    struct point *x; 
    struct point *y; 
}; 

void create_line (int srcX, int srcY, int dstX, int dstY) { 
    struct line *p; 
    struct line **q = &p; 
    (*q) = new line; 
    (*q) -> x = new point; 
    (*q) -> x -> x = new int; 
    (*q) -> x -> x = &srcX; 
    cout << *((*q)->x->x) << endl; 
    delete (*q)->x->x; // Causing run-time error 
    delete (*q)->x; 
    delete (*q); 
} 

int main(){ 
    create_line(2,3,7,8); 
    return 0; 
} 

回答

1

你似乎有此

(*q) -> x -> x = new int; 
(*q) -> x -> x = &srcX; 

第一行指出x到一個新的整數,但下一行改寫爲指向srcX,失去了以前分配的內存有些混亂。由於x指向的內容不是由new創建的,因此它不應該是delete d,因此是錯誤。

如果您已經擁有指向的內容(除非您打算將該值複製到新創建的內存中),則不需要使用new進行分配。

0

第二次分配給點結構中的x有問題。

(*q) -> x -> x = new int; // here you are allocating new memory for x 
(*q) -> x -> x = &srcX; // here you override the address you got from prev allocation 

那麼實際情況是,(*q) -> x -> x將舉行地址從new int新分配的內存讓我們說地址爲0x1000。在下一行(*q) -> x -> x將地址保持爲傳遞參數srcX讓sat 0x2000。 所以你得到的是,你使用new分配的內存地址現在已經消失了,這個內存現在已經消失了,當你到達delete (*q)->x->x時,你會得到一個錯誤,因爲會發生什麼是你試圖釋放內存您還沒有使用new進行分配。

我想你應該改變功能看起來像這樣:

void create_line (int srcX, int srcY, int dstX, int dstY) { 
    struct line *p; 
    struct line **q = &p; 
    (*q) = new line; 
    (*q) -> x = new point; 
    // (*q) -> x -> x = new int; -> no need to allocate memory 
    (*q) -> x -> x = &srcX; 
    cout << *((*q)->x->x) << endl; 
    // delete (*q)->x->x;  -> no need to free it 
    delete (*q)->x; 
    delete (*q); 
}