c - Unable to properly free malloc of another malloc -
this question has answer here:
- string assignment in c 4 answers
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,
- you face memory leak, because
malloc()ed pointer lost. - you cannot call
free()changed pointer. invokes undefined behaviour.
solution:
in c, don't assign strings, instead, can use strcpy() work done.
notes:
even in case of
strcpy()cannot use"iambananananananananananana". in case, create memory overrun destination not have enough memory hold completely.use proper format specifiers. in
printf()statements, of arguments%inot of typeint. pointer type arguments, should using%p, atleast. otherwise, ub.
Comments
Post a Comment