gpt4 book ai didi

c - Mallocing char* 与另一个 char* 长度相同会导致它成为副本吗?

转载 作者:太空宇宙 更新时间:2023-11-04 05:05:07 24 4
gpt4 key购买 nike

我目前正在尝试编写一个简单的 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;
}

然后当我使用 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

最佳答案

这段代码是错误的

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;
}

首先你需要分配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;
}

你得到相同字符串的原因是因为你将你的字符串释放回堆,然后在你调用 malloc 时再次将它取回,这纯粹是运气,另一次你可能会崩溃,得到垃圾,...

关于c - Mallocing char* 与另一个 char* 长度相同会导致它成为副本吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35232786/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com