在另一个结构中的结构内解除分配指针

Deallocating a pointer inside a structure within another structure

本文关键字:结构 解除分配 指针 另一个      更新时间:2023-10-16

我得到了以下转述的问题:"仅使用变量 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;
}

你似乎在这里有些困惑

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

第一行x指向一个新的整数,但下一行覆盖它以指向srcX,丢失先前分配的内存。由于x指向的内容不是用new创建的,因此不应该delete d,因此会出现错误。

如果您已经拥有指向的内容,则无需使用 new 进行分配(除非您打算将值复制到新创建的内存中)。

你在点结构中对 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让我们坐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);
}