在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
Run Code Online (Sandbox Code Playgroud)
那么,我的问题有三个:
malloc和memcpy?strdup但不包括memdup?小智 16
您可以通过一个简单的功能实现它:
void* memdup(const void* mem, size_t size) {
void* out = malloc(size);
if(out != NULL)
memcpy(out, mem, size);
return out;
}
Run Code Online (Sandbox Code Playgroud)
void *xmemdup (void const *p, size_t s)GNU Gnulib 中有xalloc.h.
请注意,它会xalloc_die在内存不足的情况下调用。
tva*_*son -7
复制任意内存结构并不像复制字符串那么简单。例如,当结构包含指向其他结构(例如字符串)的指针时,您应该如何处理?“复制”这样的结构意味着什么?与字符串的情况不同,这个问题没有一个正确的答案。在这种情况下,最好让应用程序开发人员创建一种根据其用例制作结构副本的机制,而不是通过假装存在规范的方法来处理问题来混淆问题。