c - Unable to properly free malloc of another malloc -


this question has answer here:

here's snippet issues.

int main() {     char** reserv = (char**)malloc(sizeof(char*)*4);     printf("%i, %i, %i, %i, %i", **reserv, *reserv, reserv, &**reserv, sizeof(char*));     int i;     for(i = 0; < 4; i++)     {         reserv[i] = (char*)calloc(sizeof(char),16);         reserv[i][15] = '\0';     }     for(i = 0; < 4; i++)         reserv[i]="iambananananananananananana";     for(i = 0; < 4; i++)         printf("\r\n>%i<", reserv[i]);     for(i = 0; < 4; i++)     {         printf("\r\n<%i>", (reserv[i]));         free(reserv[i]);     }     free(reserv); } 

this code free() working fine in 32 bit , somehow crashes horribly in 64 bit mode.

in main program i've omitted freeing members of char** causing unexptected behavior every , then, not want.

i've tried playing around addresses , pointers, tried

free(reserv+(i*sizeof(char*)) 

which failed too. can clarify i'm doing wrong?

in code

 reserv[i]="iambananananananananananana"; 

creates problem. overwrites memory allocated malloc(). thus,

  1. you face memory leak, because malloc()ed pointer lost.
  2. you cannot call free() changed pointer. invokes undefined behaviour.

solution:

in c, don't assign strings, instead, can use strcpy() work done.

notes:

  1. even in case of strcpy() cannot use "iambananananananananananana". in case, create memory overrun destination not have enough memory hold completely.

  2. use proper format specifiers. in printf() statements, of arguments %i not of type int. pointer type arguments, should using %p, atleast. otherwise, ub.


Comments

Popular posts from this blog

IF statement in MySQL trigger -

c++ - What does MSC in "// appease MSC" comments mean? -

javascript - Blogger related post gadget image Resize s72-c [ Need Expert Help ] -