Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'memdup' function in C?

Tags:

c

strdup

memcpy

In C, you can use strdup to succinctly allocate a buffer and copy a string into it. As far as I'm aware, however, there is no similar function for general memory. For example, I can't say

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

My question, then, is threefold:

  1. Is there some standard library function like this that I don't know about?
  2. If not, is there a succinct and preferably standard way to do this without explicit calls to malloc and memcpy?
  3. Why does C include strdup but not memdup?
like image 456
Dan Avatar asked Dec 01 '12 20:12

Dan


2 Answers

You can implement it whith a simple function:

void* memdup(const void* mem, size_t size) { 
   void* out = malloc(size);

   if(out != NULL)
       memcpy(out, mem, size);

   return out;
}
like image 196
Kabloc Avatar answered Oct 19 '22 15:10

Kabloc


There is void *xmemdup (void const *p, size_t s) in GNU Gnulib's xalloc.h.

Note that it calls xalloc_die in case of insufficient memory.

like image 28
Marc Avatar answered Oct 19 '22 15:10

Marc