本文介绍了我可以删除以前动态分配但具有不同指针的内存吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用C ++编写一个用于链表的程序.为了实现这一概念,我在全局创建了一个指针"start",指向列表的第一个元素.

I was making a program for linked list in C++. To implement the concept, I created a pointer 'start' globally, pointing to the first element of the list.

程序完成后,我尝试通过使用start和另一个本地声明的指针"p"访问连续的节点,来删除动态分配的所有内存,以防止内存泄漏.在这里,我使用了一个指向相同正确地址的指针,但是该指针不是用于内存分配的指针,而是像任何普通指针一样在本地声明.

After completion of the program I tried to delete all memory allocated dynamically to prevent memory leaks, by accessing successive nodes using the start and another locally declared pointer 'p'.Here, I used a pointer pointing to the same correct addresses, but this pointer was not the one used for memory allocation, but was declared locally like any normal pointer.

我的问题是-是否可以通过使用指向相同位置的普通指针来删除动态分配的内存?

My question is - Is it possible to delete the dynamically allocated memory by using the normal pointers pointing to the same location?

推荐答案

可以.这是有效的:

int* p = new int;
int* q = p;
delete q;

使用新[] 时的等效项:

int* p = new int[123];
int* q = p;
delete[] q;

用指针类型替换 int * .之后是否将指针设置为 nullptr 仍在讨论之中.

Substitute int* with your pointer type. Whether to set the pointers to nullptr afterwards is up for debate.

这篇关于我可以删除以前动态分配但具有不同指针的内存吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 09:04