指向结构和删除的指针 [英] Pointer to struct and delete

查看:74
本文介绍了指向结构和删除的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只需学习C ++并尝试正确理解指针,新指针和删除指针. 关于我的问题: 我创建了一些指向结构的指针,最后删除了它们.但是堆大小不会减少. 我搜索了一些答案,发现了以下问题. C ++删除不会释放所有内存(Windows).答案中的代码似乎可以正确释放堆.

Just learning C++ and trying to understand pointers, new, and delete correctly. About my problem: I create some pointers to a struct and at the end I delete them. But the Heap size does not decrease. I searched for some answers and found the following question.C++ delete does not free all memory (Windows). The code in the answer seems to release the Heap correctly.

我愚蠢的学习代码:

#include <iostream>

using namespace std;

struct daten
{
  int iVal;
  daten *next;
  daten *prev;
};

int main()
{
  daten *first=nullptr;
  daten *prev=nullptr;
  daten *entry=nullptr;
  daten *last=nullptr;

  cout << "[Any Key] FILL";
  getchar();

  //fill
  for( int i=0;i<100000;i++)
  {
    if(!entry)
    {
      entry=new daten;
      entry->iVal=i;
      entry->next=nullptr;
      entry->prev=nullptr;
      first=entry;
      prev=entry;
      last=entry;
    }
    else
    {
      entry=new daten;
      entry->iVal=i;
      entry->next=nullptr;
      entry->prev=prev;
      prev->next=entry;
      prev=entry;
      last=entry;
    }
  }

  cout << "[Any Key] DELETE";
  getchar();  
  //delete
  prev=last;
  while(prev)
  {
    last=prev;
    prev=prev->prev;
    delete last;
    last=nullptr;
   }

  cout << "[Any Key] END";
  getchar();
}

我有一个更复杂的代码,可以在其中插入/删除/导航为链接列表,并确保我创建了100000个这些条目,但是删除后堆不会减少. 那你能告诉我我的错误在哪里吗?

I have a more complex code where I can insert / delete / navigate as a linked list and just to be sure I created 100000 of these entries but after delete the heap does not decrease. So can you please tell me where is my mistake?

推荐答案

如果要了解程序的堆使用情况,并确保正确使用malloc/free和new/delete,则应该使用Valgrind等应用程序级工具 Memcheck .

If you want to understand the heap usage of your program, with respect to being sure you are using malloc/free and new/delete correctly, then you should be using an application-level tool like Valgrind Memcheck.

系统级工具通常会报告已为堆保留的虚拟内存量,但不一定全部提交.为堆保留的虚拟内存将在应用程序的生命周期内增加,只有在决定对其进行压缩时才会在运行时随心所欲地定期减少.

The system level tools will generally report the amount of virtual memory that has been reserved for the heap, which is not all necessarily committed. The virtual memory reserved for the heap will increase during an application's lifetime, only periodically being reduced at the whim of the runtime when it determines to compact it.

这篇关于指向结构和删除的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆