cmemcpystrdupc-standard-library

Why is there a "strdup" function, but not "memdup" function in the standard?


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?

Solution

  • Making a copy of an arbitrary memory structure isn't as straight forward as copying a string. How should you handle the case where the structure contains pointers to other structures (such as strings) for example? What does it mean to "duplicate" such a structure? There isn't one right answer to this, unlike the case for string. In that case, it's probably better to just let the application developer create a mechanism for making a copy of the structure according to their use cases rather than confuse the issue by pretending that there is a canonical way to handle it.