首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用strdup?

如何使用strdup?
EN

Stack Overflow用户
提问于 2013-02-19 08:30:49
回答 4查看 47.5K关注 0票数 12

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

代码语言:javascript
复制
char *variable;
variable = (char*) malloc(sizeof(char*));
variable = strdup(word);

我这样做对吗?还是这里出了什么问题?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2013-02-19 08:35:17

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

因此:

代码语言:javascript
复制
char *variable = strdup(word);
if (variable == 0) …process out of memory error; do not continue…
…use variable…
free(variable);

如果确实需要进行内存分配,则需要在variable中分配strlen(word)+1字节,然后可以将word复制到新分配的空间中。

代码语言:javascript
复制
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()

代码语言:javascript
复制
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()在哪里。

票数 21
EN

Stack Overflow用户

发布于 2013-02-19 08:44:25

你不需要为strdup的使用分配空间,strdup会帮你做到这一点。但是,您应该在使用后将其释放。

代码语言:javascript
复制
#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++中则不行,因为它是操作符new的保留名称。

票数 9
EN

Stack Overflow用户

发布于 2013-02-19 09:18:35

你看起来很困惑。忘掉你对指针的了解吧。让我们使用int。

代码语言:javascript
复制
int x;
x = rand();    // Let us consider this the "old value" of x
x = getchar(); // Let us consider this the "new value" of x

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

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

代码语言:javascript
复制
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);让操作系统知道你什么时候用完了malloced内存。

仅供参考,这里有一个如何实现strdup的示例:

代码语言:javascript
复制
char *strdup(const char *original) {
    char *duplicate = malloc(strlen(original) + 1);
    if (duplicate == NULL) { return NULL; }

    strcpy(duplicate, original);
    return duplicate;
}
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14947821

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档