malloc()函数分配的内存寿命

时间:2018-12-31 16:19:47

标签: c pointers malloc

如果我将一个指针传递给函数,该指针从该指针获取分配给内存的地址,那么函数退出时是否释放了内存?

void initWomenList(Women **head, Women *headWoman) {        
  headWoman = (Women *) malloc(sizeof(Women));
  if (headWoman == NULL) {
      printf("Allocation of headWoman failed\n");
      exit(1);
  }
  headWoman->userWoman = NULL;
  headWoman->next = NULL;

  head = &headWoman;
}

函数返回时,head和headWoman都为NULL吗?

1 个答案:

答案 0 :(得分:7)

在C语言中没有自动内存释放(有时称为垃圾收集器)。必须使用malloc/calloc/realloc函数手动释放分配给free的所有内存。

C语言中的所有函数参数均按值传递,因此在函数内部分配headWomen在外部不起作用,并且由于没有指针持有分配的内存,因此当前存在内存泄漏

void
alloc_mem(int* a) {
    a = malloc(sizeof(*a));
}

//usage in your case
int* a;
//Function will allocate memory for single int, but it won't be saved to variable a.
alloc_mem(a);

更好的方法是使用 pointer-to-pointer 或从函数中返回 pointer

int*
alloc_mem() {
    return malloc(sizeof(int));
}

//usage
int* a = alloc_mem();
if (a != NULL) {
    //Check if null
}

或使用指针到指针方法

void
alloc_mem(int** a) {
    *a = malloc(sizeof(**a));
}

//usage
int* a;
alloc_mem(&a);
if (a != NULL) {
    //Do the job.
}

在所有这些操作结束时,请始终调用free函数

free(a);

如果我回到最初的示例,则必须将函数重写为如下形式:

void 
//Notice here **headWoman instead of *headWoman
initWomenList(Women **head, Women **headWoman) {  
  //Notice here *headWoman instead of headWoman      
  *headWoman = malloc(sizeof(Women));
  if (headWoman == NULL) {
      printf("Allocation of headWoman failed\n");
      exit(1);
  }
  headWoman->userWoman = NULL;
  headWoman->next = NULL;

  //Notice here *head instead of head
  *head = &headWoman;
}

和用法:

Woman* headWoman;
Woman* head;

initWomenList(&head, &headWoman);
//Don't forget to free memory after usage.