如何使用strdup?

13

我正在调用 strdup 函数,在调用 strdup 之前需要为变量分配空间。

char *variable;
variable = (char*) malloc(sizeof(char*));
variable = strdup(word);

我这样做对吗?还是有什么地方出了问题?

4个回答

22
如果你正在使用POSIX标准的strdup()函数,它会计算所需空间并分配内存,并将源字符串复制到新分配的空间中。你不需要自己使用malloc()函数,如果你这样做了,它会立即泄漏,因为你覆盖了指向你分配的空间的唯一指针,而这个指针应该指向strdup()分配的空间。因此:
char *variable = strdup(word);
if (variable == 0) …process out of memory error; do not continue…
…use variable…
free(variable);
如果您确实需要进行内存分配,则需要在variable中分配strlen(word)+1字节,并将word复制到该新分配的空间中。
char *variable = malloc(strlen(word)+1);
if (variable == 0) …process out of memory error; do not continue…
strcpy(variable, word);
…use variable…
free(variable);

或者计算一次长度,然后使用memmove()或者也许是memcpy():

size_t len = strlen(word) + 1;
char *variable = malloc(len);
if (variable == 0) …process out of memory error; do not continue…
memmove(variable, word, len);
…use variable…
free(variable);

不要忘记确保你知道每个malloc()对应的free()在哪里。


9

使用strdup时不需要为其分配空间,它会自动为您分配。但是在使用后应该释放它。

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

int main (){

    const char* s1= "Hello World";
    char* new = strdup (s1);
    assert (new != NULL);

    fprintf( stdout , "%s\n", new);

    free (new);
    return 0;
}

编辑:使用C++时要注意,变量名new在C语言中是可以的,但在C++中不行,因为它是operator new的保留名称。


不应将“new”用作变量名称。 - albttx
1
@ale-batt 在 C 语言中,这个变量名是完全没问题的。但我可以理解 C++ 编译器不喜欢它。这个问题被标记为 C 语言,因此我认为没有问题。 - hetepeperfan

6

你似乎有些困惑。把关于指针的知识先放一边,我们现在只考虑整数。

int x;
x = rand();    // Let us consider this the "old value" of x
x = getchar(); // Let us consider this the "new value" of x

有没有办法让我们获取旧值,或者它已经从我们的视图中“泄漏”了?假设你需要告诉操作系统你已经完成了那个随机数,以便操作系统执行一些清理任务。

生成新值是否需要旧值?当getchar看不到x时,它怎么可能需要呢?

现在让我们考虑你的代码:

char *variable;
variable = (char*) malloc(sizeof(char*)); // Let us consider this the "old value" of variable
variable = strdup(word);                  // Let us consider this the "new value" of variable

我们有没有办法检索旧的值,或者说它已经从我们的视野中"泄漏"了?当您调用free(variable);释放malloc的内存时,您需要让操作系统知道您已经完成了。

生成新值是否需要旧值?strdup无法获取变量,那么它如何生成新值呢?

这里是一个关于如何实现strdup的示例供参考:

char *strdup(const char *original) {
    char *duplicate = malloc(strlen(original) + 1);
    if (duplicate == NULL) { return NULL; }

    strcpy(duplicate, original);
    return duplicate;
}

2
目前情况下,您始终会泄露4到8个字节(取决于您的架构)。无论使用strdup是否分配所需的动态内存,您都将重新分配仅保存指向新分配的内存区域指针的唯一变量。简单地说,
char* const variable = strdup(word);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接