C语言 我如何使用 strdup?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14947821/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:23:35  来源:igfitidea点击:

How do I use strdup?

cmallocstrdup

提问by Ivan Zhang

I am calling strdupand have to allocate space for the variable before calling strdup.

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

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

Am I doing this right? Or is there something wrong here?

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

回答by Jonathan Leffler

If you're using the POSIX standard strdup(), it calculates the space needed and allocates it and copies the source string into the newly allocated space. You don't need to do a malloc()yourself; indeed, it immediately leaks if you do it since you overwrite the only pointer to the space you allocated with the pointer to the space that strdup()allocated.

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

Hence:

因此:

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

If you do need to do the memory allocation, then you need to allocate strlen(word)+1bytes in variableand you can then copy wordinto that newly allocated space.

如果确实需要进行内存分配,则需要在其中分配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);

Or calculate the length once and use memmove()or perhaps memcpy():

或者计算一次长度并使用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);

Don't forget to ensure you know where the free()is for every malloc().

不要忘记确保您知道free()每个malloc().

回答by hetepeperfan

you don't need to alloc space for use with strdup, strdup will do that for you. However you should free it after use.

你不需要为 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;
}

Edit: Be carefull with C++ as the variable name new is fine in C and not in C++ since it is a reserved name for operator new.

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

回答by autistic

You seem confused. Forget what you know about pointers. Let's work with ints.

你看起来很困惑。忘记你对指针的了解。让我们使用整数。

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

Is there any way for us to retrieve the old value, or has it "leaked" from our view? As a hypothetical, suppose you were expected to let the OS know that you're finished with that random number, in order for the OS to perform some cleanup tasks.

有没有办法让我们检索旧值,或者它是否从我们的视图中“泄露”了?作为假设,假设您应该让操作系统知道您已完成该随机数,以便操作系统执行一些清理任务。

Is the old value required for the generation of the new value? How can it be, when getcharcan't see x?

生成新值是否需要旧值?怎么可能,什么时候getchar看不见x?

Let us now consider your code:

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

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

Is there any way for us to retrieve the old value, or has it "leaked" from our view? You're expected to let the OS know when you're finished with malloced memory, by calling free(variable);.

有没有办法让我们检索旧值,或者它是否从我们的视图中“泄露”了?当您完成malloced 内存时,您应该通过调用free(variable);.

Is the old value required for the generation of the new value? How can it be, when strdupcan't see variable?

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

FYI, here's an example of how strdup might be implemented:

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

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

    strcpy(duplicate, original);
    return duplicate;
}

回答by bitmask

As it currently stands you are always leaking 4 to 8 bytes (depending on your architecture). Regardless of strdupwhich will allocate the required dynamic memory on its ownyou are reassigning the only variable that holds the pointer to your newly malloced memory area.

就目前而言,您总是会泄漏 4 到 8 个字节(取决于您的架构)。无论strdup哪个将自行分配所需的动态内存,您都将重新分配唯一保存指向新分配的内存区域的指针的变量。

Simply say

简单的说

char* const variable = strdup(word);