调用free()后内存未释放

Sha*_*ant 2 memory malloc free memory-leaks

我有一个简短的程序,通过向其添加节点来生成链接列表,然后释放链接列表分配的内存.

Valgrind不报告任何内存泄漏错误,但该过程继续保持分配的内存.

在将sizeof(structure_name)分配的内存更改为固定数512后,我才能修复错误.(请参阅注释代码)

这是一个错误还是正常的操作?这是代码:

#include <execinfo.h>
#include <stdlib.h>
#include <stdio.h>


typedef struct llist_node {
  int ibody;
  struct llist_node * next;
  struct llist_node * previous;
  struct llist * list;
}llist_node;

typedef struct  llist {
  struct llist_node * head;
  struct llist_node * tail;
  int id;
  int count;
}llist;

llist_node * new_lnode (void) {
  llist_node * nnode = (llist_node *) malloc ( 512 );
  //  llist_node * nnode = (llist_node *) malloc ( sizeof(llist_node) );
  nnode->next = NULL;
  nnode->previous = NULL;
  nnode->list = NULL;
  return nnode;
}

llist * new_llist (void) {
  llist * nlist = (llist *) malloc ( 512 );
  //  llist * nlist = (llist *) malloc ( sizeof(llist) );
  nlist->head = NULL;
  nlist->tail = NULL;
  nlist->count = 0;
  return nlist;
}

void add_int_tail ( int ibody, llist * list ) {
  llist_node * nnode = new_lnode();
  nnode->ibody = ibody;
  list->count++;
  nnode->next = NULL;
  if ( list->head == NULL ) {
    list->head = nnode;
    list->tail = nnode;
  }
  else {
    nnode->previous = list->tail;
    list->tail->next = nnode;
    list->tail = nnode;
  }
}

void destroy_list_nodes ( llist_node * nodes ) {
  llist_node * llnp = NULL;
  llist_node * llnpnext = NULL;
  llist_node * llnp2 = NULL;
  if ( nodes == NULL )
    return;
  for ( llnp = nodes; llnp != NULL; llnp = llnpnext ) {
    llnpnext = llnp->next;
    free (llnp);
  }
  return;
}

void destroy_list ( llist * list ) {
  destroy_list_nodes ( list->head );
  free (list);
}

int main () {
  int i = 0;
  int j = 0;
  llist * list = new_llist ();

  for ( i = 0; i < 100; i++ ) {
    for ( j = 0; j < 100; j++ ) {
      add_int_tail ( i+j, list );
    }
  }
  printf("enter to continue and free memory...");
  getchar();
  destroy_list ( list );
  printf("memory freed. enter to exit...");
  getchar();
  printf( "\n");
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

Gar*_*han 5

如果"进程继续保持分配的内存"意味着ps不会报告进程内存使用量的减少,那就完全正常了.由于各种原因,将内存返回到进程的堆并不一定会使进程将其返回到操作系统.如果你在一个大循环中一遍又一遍地创建和销毁你的列表,并且你的进程的内存使用量不会无限制地增长,那么你可能没有真正的内存泄漏.

[编辑添加:另请参阅malloc实现是否会将free-ed内存返回给系统?]

[EDITED再次补充说:顺便提一下,分配512字节块的最可能原因是问题消失了,你的malloc实现特别以某种方式处理更大的块,这使得它更容易注意到整个页面都没有更长时间的使用 - 如果要将任何内存返回到操作系统,这是必要的.