Memory leaking in C, malloc inside function -


i trying create 2d array of struct grid_t, , getting memory leak warnings via address sanitiser, , seg fault in conditions.

there may various points in code causing this, thought knowing going wrong here point me in right direction fixing rest.

i new c , memory management, feedback welcome , appreciated!

void creategridarray(atom_t* atom) {   atom -> grid = (grid_t**) malloc(width * sizeof(grid_t*));    grid_t *nullgrid = malloc(sizeof(grid_t));   grid_t temp = {null, 0};   *nullgrid = temp;     (int = 0; < width; i++) {     (atom -> grid)[i] = malloc(height * sizeof(grid_t));     (int j = 0; j < height; j++) {         (atom -> grid)[i][j] = *nullgrid;     }   }   //free(nullgrid); <- do now?   return; } 

firstly, don't cast return malloc(). not required in c, , can obscure serious errors.

second, don't hard-code type malloc() call. example,

atom->grid = (grid_t**) malloc(width * sizeof(grid_t*)); 

would replaced

atom->grid = malloc(width * sizeof(*(atom->grid))); 

this ensures memory allocated of required size, regardless of atom->grid pointer to.

to answer question, release memory, need pass every nonnull pointer returned malloc() free(). once.

so, if allocate this

atom->grid = malloc(width * sizeof(*(atom->grid)));  grid_t *nullgrid = malloc(sizeof(*nullgrid)); grid_t temp = {null, 0}; *nullgrid = temp;  (int = 0; < width; i++) {     (atom -> grid)[i] = malloc(height * sizeof(*((atom->grid)[i])));     (int j = 0; j < height; j++) {         (atom -> grid)[i][j] = *nullgrid; } 

the 1 way of deallocating be

for (int = 0; < width; i++) {     free((atom -> grid)[i]); } free(atom->grid); free(nullgrid); 

in case, cannot safely free(atom->grid) before free((atom -> grid)[i]) (unless store of (atom->grid)[i] somewhere else, sort of defeats point). individual (atom->grid)[i] may freed in order (as long each released once).

lastly, check pointers returned malloc(). returns null when fails, , dereferencing null pointer gives undefined behaviour.


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -