在 C 中,您可以使用 strdup
简洁地分配缓冲区并将字符串复制到其中。然而,据我所知,一般内存没有类似的功能。例如,我不能说
struct myStruct *foo = malloc(sizeof(struct myStruct));
fill_myStruct(foo);
struct myStruct *bar = memdup(foo, sizeof(struct myStruct));
// bar is now a reference to a new, appropriately sized block of memory,
// the contents of which are the same as the contents of foo
那么,我的问题有三个方面:
- 有没有像这样的标准库函数是我不知道的?
- 如果没有,是否有一种简洁且最好是标准的方法来执行此操作而无需显式调用
malloc
和memcpy
? - 为什么 C 包含
strdup
但不包含memdup
?
最佳答案
你可以用一个简单的函数来实现它:
void* memdup(const void* mem, size_t size) {
void* out = malloc(size);
if(out != NULL)
memcpy(out, mem, size);
return out;
}
关于c - C中的'memdup'函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13663617/