xref: /netbsd-src/external/gpl3/gdb/dist/libiberty/xmemdup.c (revision 4b169a6ba595ae283ca507b26b15fdff40495b1c)
1ba340e45Schristos /* xmemdup.c -- Duplicate a memory buffer, using xmalloc.
298b9484cSchristos    This trivial function is in the public domain.
398b9484cSchristos    Jeff Garzik, September 1999.  */
498b9484cSchristos 
598b9484cSchristos /*
698b9484cSchristos 
798b9484cSchristos @deftypefn Replacement void* xmemdup (void *@var{input}, @
898b9484cSchristos   size_t @var{copy_size}, size_t @var{alloc_size})
998b9484cSchristos 
1098b9484cSchristos Duplicates a region of memory without fail.  First, @var{alloc_size} bytes
1198b9484cSchristos are allocated, then @var{copy_size} bytes from @var{input} are copied into
1298b9484cSchristos it, and the new memory is returned.  If fewer bytes are copied than were
1398b9484cSchristos allocated, the remaining memory is zeroed.
1498b9484cSchristos 
1598b9484cSchristos @end deftypefn
1698b9484cSchristos 
1798b9484cSchristos */
1898b9484cSchristos 
1998b9484cSchristos #ifdef HAVE_CONFIG_H
2098b9484cSchristos #include "config.h"
2198b9484cSchristos #endif
2298b9484cSchristos #include "ansidecl.h"
2398b9484cSchristos #include "libiberty.h"
2498b9484cSchristos 
2598b9484cSchristos #include <sys/types.h> /* For size_t. */
2698b9484cSchristos #ifdef HAVE_STRING_H
2798b9484cSchristos #include <string.h>
2898b9484cSchristos #else
2998b9484cSchristos # ifdef HAVE_STRINGS_H
3098b9484cSchristos #  include <strings.h>
3198b9484cSchristos # endif
3298b9484cSchristos #endif
3398b9484cSchristos 
34*4b169a6bSchristos void *
xmemdup(const void * input,size_t copy_size,size_t alloc_size)35*4b169a6bSchristos xmemdup (const void *input, size_t copy_size, size_t alloc_size)
3698b9484cSchristos {
37*4b169a6bSchristos   void *output = xmalloc (alloc_size);
38ba340e45Schristos   if (alloc_size > copy_size)
39ba340e45Schristos     memset ((char *) output + copy_size, 0, alloc_size - copy_size);
40*4b169a6bSchristos   return (void *) memcpy (output, input, copy_size);
4198b9484cSchristos }
42