我正在调用strdup,并且在调用strdup之前必须为变量分配空间。
char *variable;
variable = (char*) malloc(sizeof(char*));
variable = strdup(word);我这样做对吗?还是这里出了什么问题?
发布于 2013-02-19 08:35:17
如果您使用的是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()在哪里。
发布于 2013-02-19 08:44:25
你不需要为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;
}编辑:要小心使用C++,因为变量名new在C中可以使用,而在C++中则不行,因为它是操作符new的保留名称。
发布于 2013-02-19 09:18:35
你看起来很困惑。忘掉你对指针的了解吧。让我们使用int。
int x;
x = rand(); // Let us consider this the "old value" of x
x = getchar(); // Let us consider this the "new value" of 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);让操作系统知道你什么时候用完了malloced内存。
仅供参考,这里有一个如何实现strdup的示例:
char *strdup(const char *original) {
char *duplicate = malloc(strlen(original) + 1);
if (duplicate == NULL) { return NULL; }
strcpy(duplicate, original);
return duplicate;
}https://stackoverflow.com/questions/14947821
复制相似问题