Free dynamically created 3d array in C -
none of answers have found seem address issue. creating dynamic 3d array in c , later freeing it. can store , later access data stored in array using nested loop access violation when trying free using same nested loop setup. going wrong?
unsigned char ***buff1; int r, c; somefunction(&buff1, &r, &c); for(int = 0; < r; ++i) { for(int j = 0; j < c; ++j) { free(buff1[i][j]); } free(buff1[i]); } free(buff1); somefunction(unsigned char**** buff, int *nr, int *nc) { ... *buff = (sqlchar***)malloc(*nr * sizeof(sqlchar**)); for(int = 0; < *nr; ++i) { (*buff)[i] = (sqlchar**)malloc(*nc * sizeof(sqlchar**)); for(int j = 0; j < *nc; ++j) { (*buff)[i][j] = (sqlchar*)malloc(256); } } }
multiple things wrong:
unsigned char**** buff
what this, if not wrong? (well, ok, not technically, stylistically anyway...)
(sqlchar*)malloc(256);
isn't better either, since you must not cast return value of malloc()
in c.
the third mistake don't have 3d array. have pointer-to-pointer-to-pointer. ewww. ugly. why not allocate true 3d array instead?
size_t xsize, ysize, zsize; // initialize these! unsigned char (*arr)[ysize][zsize] = malloc(sizeof(*arr) * xsize);
then need in order free is:
free(arr);
honestly, isn't way better?
Comments
Post a Comment