在结构上的一系列新/删除之后,我似乎有记忆丧失

Try*_*yer 1 c++

我有一个结构的链表,每个结构包含一个整数和一个指向下一个结构的指针.在通过一系列新命令填充此结构之前,我在Windows任务管理器的"内存使用情况"下记下此程序使用的内存(例如Mem_1).接下来发生实际的链表创建.(参见下面的void populate(int i)函数).然后,我使用一系列删除尝试删除此链接列表,并希望回收内存.删除后,我在任务管理器中再次检查内存.这次使用的内存量是Mem_2.我注意到Mem_2> Mem_1.不应该Mem_2 = Mem_1?或者是否有一些悬垂的指针,我没有妥善处理.

感谢您提前的帮助...(代码是控制台应用程序/ VS2008/Windows XP平台)

struct item_s{
int value;
item_s* next;
};

struct item_s* item = NULL;
struct item_s* last_item = NULL;
struct item_s* last_accessed = NULL;

void populate(int i){
     if(item == NULL){
    item = new item_s;
    item->value = i;
    item->next = NULL;
    last_item = item;
}
else{
    last_item->next = new item_s;
    last_item->next->value = i;
    last_item->next->next = NULL;
    last_item = last_item->next;
}
}

void main(){
for(i = 1; i <= 10000; i++){
    populate(i);
}
last_item = item;
last_accessed = last_item->next;
while(last_item!=NULL){
    delete last_item;
    last_item = last_accessed;
    if(last_item!=NULL){
        last_accessed = last_item->next;
    }
}
}
Run Code Online (Sandbox Code Playgroud)

Bil*_*eal 5

这里有两大问题:

  1. 你为什么new荷兰国际集团struct小号呢?您可能应该使用某种形式或RAII容器.如果你是,你根本不必担心内存泄漏(当然,除非容器中有错误)例子包括std::vectorstd::auto_ptr.如果你有机会获得的C++ 0x也有std::unique_ptrstd::shared_ptr.如果您只能访问TR1(或升级库),可用的类似容器是std::tr1::shared_ptr,和std::tr1::scoped_ptr.(boost::在增强版中的名称空间中)
  2. Windows的任务管理器报告该进程消耗的虚拟内存.该delete调用仅将内存返回给C运行时.C运行时并不总是立即将内存返回给操作系统,因为OS分配(通过VirtualAlloc)非常昂贵.
  3. 是的int main()!

要确定是否实际分配了内存,您需要该工具在C运行时级别运行,而不是在操作系统级别运行.