简体   繁体   中英

The lifespan of memory allocated by the malloc() function

If I pass to a function a pointer where the pointer gets an address to allocated memory, is the memory freed when the function exits?

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;
}

Are both head and headWoman NULL when the function returns?

There is no automatic memory deallocation (sometimes called garbage collector ) in the C language. Any memory allocated with malloc/calloc/realloc must be manually freed using free function.

All function parameters in C language are passed by value, thus assigning headWomen inside function has no effect outside and currently you have memory leak because no pointer is holding allocated memory.

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);

Better is to either use pointer-to-pointer or return pointer from function.

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

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

Or with pointer-to-pointer approach

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

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

At the end of all these operations, always call free function

free(a);

If I go back to your initial example, you have to rewrite function to something like this:

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;
}

And usage:

Woman* headWoman;
Woman* head;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM