我目前正在尝试编写一个简单的C程序,它创建一个带有char*字段的结构,并将其赋值为与argv [1]相同的值.然后我想创建另一个与argv [1]长度相同的char*,但由于某种原因,里面的数据已经包含与argv [1]相同的值.到目前为止,这是我的代码:
#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 is this a 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;
}
Run Code Online (Sandbox Code Playgroud)
然后,当我使用GCC 6.1编译并运行该程序时,我得到了这个
> gcc -Wall -g -o test test.c
> ./test "test value here"
> original: test value here
> why is this a copy? test value here
Run Code Online (Sandbox Code Playgroud)
这段代码错了
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;
}
Run Code Online (Sandbox Code Playgroud)
首先你需要分配strlen + 1
其次你不能在这里免费'复制',p-> str指向它,你现在有一个悬空指针.复制和malloc使用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;
}
Run Code Online (Sandbox Code Playgroud)
您获得相同字符串的原因是因为您将字符串释放回堆中,然后在调用malloc时再次将其恢复,这纯粹是运气,另一次您可能崩溃,垃圾,......