我如何使用strdup?

Iva*_*ang 12 c malloc strdup

我正在调用strdup,必须在调用之前为变量分配空间strdup.

char *variable;
variable = (char*) malloc(sizeof(char*));
variable = strdup(word);
Run Code Online (Sandbox Code Playgroud)

我这样做了吗?或者这里有什么问题吗?

Jon*_*ler 21

如果您正在使用POSIX标准strdup(),它会计算所需的空间并分配它并将源字符串复制到新分配的空间中.你不需要malloc()自己做; 实际上,如果你这样做会立即泄漏,因为你用你指向分配空间的指针覆盖了你指定空间的唯一指针strdup().

因此:

char *variable = strdup(word);
if (variable == 0) …process out of memory error; do not continue…
…use variable…
free(variable);
Run Code Online (Sandbox Code Playgroud)

如果确实需要进行内存分配,则需要分配strlen(word)+1字节,variable然后可以复制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);
Run Code Online (Sandbox Code Playgroud)

或计算一次长度并使用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);
Run Code Online (Sandbox Code Playgroud)

不要忘记确保你知道free()每个人的位置malloc().


het*_*fan 9

你不需要为strdup分配空间,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;
}
Run Code Online (Sandbox Code Playgroud)

编辑:小心使用C++,因为变量名new在C中很好而不是在C++中,因为它是operator new的保留名称.


aut*_*tic 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
Run Code Online (Sandbox Code Playgroud)

我们有什么方法可以检索旧值,还是从我们的视角"泄露"?作为一个假设,假设您希望操作系统知道您已完成该随机数,以便操作系统执行一些清理任务.

是否需要生成新值所需的旧值?怎么可能,什么时候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
Run Code Online (Sandbox Code Playgroud)

我们有什么方法可以检索旧值,还是从我们的视角"泄露"?malloc通过调用,您可以通过操作系统获知操作系统free(variable);.

是否需要生成新值所需的旧值?怎么可能,什么时候strdup看不到变量?

仅供参考,以下是如何实施strdup的示例:

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

    strcpy(duplicate, original);
    return duplicate;
}
Run Code Online (Sandbox Code Playgroud)