xmemdup.c 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. /* xmemdup.c -- Duplicate a memory buffer, using xmalloc.
  2. This trivial function is in the public domain.
  3. Jeff Garzik, September 1999. */
  4. /*
  5. @deftypefn Replacement void* xmemdup (void *@var{input}, @
  6. size_t @var{copy_size}, size_t @var{alloc_size})
  7. Duplicates a region of memory without fail. First, @var{alloc_size} bytes
  8. are allocated, then @var{copy_size} bytes from @var{input} are copied into
  9. it, and the new memory is returned. If fewer bytes are copied than were
  10. allocated, the remaining memory is zeroed.
  11. @end deftypefn
  12. */
  13. #ifdef HAVE_CONFIG_H
  14. #include "config.h"
  15. #endif
  16. #include "ansidecl.h"
  17. #include "libiberty.h"
  18. #include <sys/types.h> /* For size_t. */
  19. #ifdef HAVE_STRING_H
  20. #include <string.h>
  21. #else
  22. # ifdef HAVE_STRINGS_H
  23. # include <strings.h>
  24. # endif
  25. #endif
  26. PTR
  27. xmemdup (const PTR input, size_t copy_size, size_t alloc_size)
  28. {
  29. PTR output = xmalloc (alloc_size);
  30. if (alloc_size > copy_size)
  31. memset ((char *) output + copy_size, 0, alloc_size - copy_size);
  32. return (PTR) memcpy (output, input, copy_size);
  33. }