c - C中的'memdup'函数?

标签 c memcpy strdup

在 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

那么,我的问题有三个方面:

  1. 有没有像这样的标准库函数是我不知道的?
  2. 如果没有,是否有一种简洁且最好是标准的方法来执行此操作而无需显式调用 mallocmemcpy
  3. 为什么 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/

相关文章:

c - 重叠指针、类型的限制限定符的粒度

c - memcpy 混淆溢出/用 gcc 覆盖?

c - 如何防止 memcpy 缓冲区溢出?

c - strdup() - 它在 C 中的作用是什么?

c - 用 C 打印一个图案

C++浮点精度

c - 查找 C 库中的函数列表

C++ 使用 memcpy 填充结构中的 vector

c - Linux 上的 strdup 使用哪个宏?