【问题标题】:Does a pointer get the same memory address after deleting it and allocating new memory again in c++?指针在删除它并在c ++中再次分配新内存后是否获得相同的内存地址?
【发布时间】:2016-07-11 15:45:15
【问题描述】:

这是我想澄清的事情。我有另一个显示链接的功能。调用该显示函数后,我的控制台上出现了一个垃圾值。 但是当我评论“删除临时”语句时它工作正常,我得到了预期的结果。请帮忙。谢谢。

void MyLinkedList::insertFirst(double data){
    MyLink *temp = new MyLink(data);
    temp->next = first;
    first = temp;
    delete temp;
}

【问题讨论】:

  • delete temp; 会处理先前使用new 分配的内存,因此一旦函数返回first 将指向未分配的内存。任何通过 first 指针访问数据的尝试都会导致 UB(未定义行为)。
  • @dxiv 感谢您的评论。

标签: c++ pointers visual-c++ memory-management memory-address


【解决方案1】:

删除操作符不是删除指针本身,而是删除它所指向的内存。

 MyLink *temp = new MyLink(data); //allocate space for a MyLink dataType
 first=tmp; //temp still points to the allocated space
 delete temp; //deallocate the memory space pointed by temp which is the same memory space pointed by first.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-04
    • 2020-08-15
    • 2014-10-03
    • 2012-08-05
    • 2014-11-27
    • 1970-01-01
    • 2019-04-07
    • 2019-09-17
    相关资源
    最近更新 更多