在另一个结构中的结构内解除分配指针
Deallocating a pointer inside a structure within another structure
我得到了以下转述的问题:"仅使用变量 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);
}
相关文章:
- 指针会被解除分配吗?
- 基于浅树的数据结构的内存分配器,用于频繁分配和解除分配
- 解除分配矩形 2D 数组会根据尺寸产生错误
- 为什么在正确解除分配内存时出现内存泄漏?
- 堆栈变量超出范围时是否解除分配?
- 如何在不使用 "new" 关键字的情况下解除分配创建的对象的内存?
- 在 QStandardItemModel 中解除分配项目
- 在 c++ 中将一种结构类型分配给另一种类型
- 解除分配此特定 2D 阵列的内存
- C++删除数组只会解除分配第一项
- C++类内部结构动态分配的方法
- char*在结构内存分配中
- 在 c++ 中使用向量解除分配
- 与解除分配堆数组相关的语法混淆
- 解除分配与 C++ 中的结构关联的所有内存
- 是否随作用域分配和解除分配堆栈帧
- 如果我使用 std::function 来捕获 lambda,我应该担心它被解除分配吗?
- 如果清除了 std::map 是否确保内存被解除分配
- 在另一个结构中的结构内解除分配指针
- 由 strcpy 设置的解除分配字符 * 时内存泄漏?