xref: /netbsd-src/external/gpl3/binutils/dist/libiberty/xmemdup.c (revision 4f645668ed707e1f969c546666f8c8e45e6f8888)
18cbf5cb7Schristos /* xmemdup.c -- Duplicate a memory buffer, using xmalloc.
22a6b7db3Sskrll    This trivial function is in the public domain.
32a6b7db3Sskrll    Jeff Garzik, September 1999.  */
42a6b7db3Sskrll 
52a6b7db3Sskrll /*
62a6b7db3Sskrll 
7883529b6Schristos @deftypefn Replacement void* xmemdup (void *@var{input}, @
8883529b6Schristos   size_t @var{copy_size}, size_t @var{alloc_size})
92a6b7db3Sskrll 
102a6b7db3Sskrll Duplicates a region of memory without fail.  First, @var{alloc_size} bytes
112a6b7db3Sskrll are allocated, then @var{copy_size} bytes from @var{input} are copied into
122a6b7db3Sskrll it, and the new memory is returned.  If fewer bytes are copied than were
132a6b7db3Sskrll allocated, the remaining memory is zeroed.
142a6b7db3Sskrll 
152a6b7db3Sskrll @end deftypefn
162a6b7db3Sskrll 
172a6b7db3Sskrll */
182a6b7db3Sskrll 
192a6b7db3Sskrll #ifdef HAVE_CONFIG_H
202a6b7db3Sskrll #include "config.h"
212a6b7db3Sskrll #endif
222a6b7db3Sskrll #include "ansidecl.h"
232a6b7db3Sskrll #include "libiberty.h"
242a6b7db3Sskrll 
252a6b7db3Sskrll #include <sys/types.h> /* For size_t. */
262a6b7db3Sskrll #ifdef HAVE_STRING_H
272a6b7db3Sskrll #include <string.h>
282a6b7db3Sskrll #else
292a6b7db3Sskrll # ifdef HAVE_STRINGS_H
302a6b7db3Sskrll #  include <strings.h>
312a6b7db3Sskrll # endif
322a6b7db3Sskrll #endif
332a6b7db3Sskrll 
34*4f645668Schristos void *
xmemdup(const void * input,size_t copy_size,size_t alloc_size)35*4f645668Schristos xmemdup (const void *input, size_t copy_size, size_t alloc_size)
362a6b7db3Sskrll {
37*4f645668Schristos   void *output = xmalloc (alloc_size);
388cbf5cb7Schristos   if (alloc_size > copy_size)
398cbf5cb7Schristos     memset ((char *) output + copy_size, 0, alloc_size - copy_size);
40*4f645668Schristos   return (void *) memcpy (output, input, copy_size);
412a6b7db3Sskrll }
42