c - How to free a two dimensional array using malloc -


i have array has 6 elements. , each of 6 elements have 40 elements. wondering when free malloced memory, have free both or can free main layer ( 1 containing 6 elements) automatically free other secondary array?

 char ** listofdetails;  //first array     listofdetails = malloc(sizeof(char*)*6);      for(i=0;i<6;i++)     {     listofdetails[i] = malloc(sizeof(char)*40); // secondary array     fgets(listofdetails[i], 40, fp);     } 

you need destroying function like

 void destroy_array_of_cstrings (char**lis, size_t siz)  {     if (!lis) return;     (size_t ix=0; ix<siz; ix++) free (lis[ix]);     free (lis);  } 

you'll call destroy_array_cstring(listofdetails, 6) in your case. alfred hang answered, should clear listofdetails after: listofdetails=null; avoid accidentally free-ing pointer twice, or dereferencing freed pointer.

you'll better use calloc allocation of array of pointers (you want each of them initialized null, calloc in practice).

see this answer question mentionning listeofdetails 6 (so guess same homework).

btw, might later use boehm's conservative garbage collector: use gc_malloc, gc_strdup , won't bother free-ing anymore. discuss teacher.


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -