使用与另一个char*相同长度的mallocing char*会导致它成为副本吗?

use*_*388 0 c gcc

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

pm1*_*100 7

这段代码错了

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时再次将其恢复,这纯粹是运气,另一次您可能崩溃,垃圾,......

  • 取决于你想要做什么.当你不再需要它时你需要释放字符串.如果你过早释放它,你会得到奇怪的行为,包括崩溃和腐败.如果你太晚解除了内存泄漏 - 欢迎来到C (2认同)
  • 在c没有任何事情发生魔术,释放p不会释放p指向的任何东西,它不知道你没有另一个指针指向相同的字符串.但在你的情况下你应该自由(p-> str); 自由(P); 我们知道p-> str是一个'私人'副本 (2认同)