c - Mallocing char* with same length as another char* causes it become a copy? -
i trying write simple c program creates struct char* field , assigns have same value argv[1]. want create char* same length argv[1], reason data inside contains same value argv[1]. here code far:
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <ctype.h> struct example{ char *str; }; struct example* create(char *s){ struct example *p = (struct example*)malloc(sizeof(struct example)); char * copy = (char*)malloc(strlen(s)); strcpy(copy, s); p->str = copy; free(copy); return p; } void new_char(struct example * t){ printf("original: %s\n", t->str); char *w = (char *)malloc(strlen(t->str)); printf("why copy? %s\n", w); free(w); } void clean(struct example *t){ free(t); } int main(int argc, char **argv){ struct example * p = create(argv[1]); new_char(p); clean(p); return 0; }
then when compile , run program using gcc 6.1, out put
> gcc -wall -g -o test test.c > ./test "test value here" > original: test value here > why copy? test value here
this code wrong
struct example* create(char *s){ struct example *p = (struct example*)malloc(sizeof(struct example)); char * copy = (char*)malloc(strlen(s)); strcpy(copy, s); p->str = copy; free(copy); return p; }
first need allocate strlen + 1
second cannot free 'copy' here, p->str points @ it, have dangling pointer. copy , malloc use strdup http://linux.die.net/man/3/strdup
struct example* create(char *s){ struct example *p = (struct example*)malloc(sizeof(struct example)); p->str = strdup(s); return p; }
the reason got same string because released string heap , got again when called malloc, purely luck, time might crash, garbage,...
Comments
Post a Comment