xmalloc.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. * Author: Tatu Ylonen <ylo@cs.hut.fi>
  3. * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
  4. * All rights reserved
  5. * Versions of malloc and friends that check their results, and never return
  6. * failure (they call fatal if they encounter an error).
  7. *
  8. * As far as I am concerned, the code I have written for this software
  9. * can be used freely for any purpose. Any derived versions of this
  10. * software must be clearly marked as such, and if the derived work is
  11. * incompatible with the protocol description in the RFC file, it must be
  12. * called by a name other than "ssh" or "Secure Shell".
  13. */
  14. #include <string.h>
  15. #include <stdlib.h>
  16. #include "conf.h"
  17. #include "xmalloc.h"
  18. #include "error.h"
  19. void *
  20. xmalloc(size_t size)
  21. {
  22. void *ptr;
  23. if (size == 0)
  24. fatal("xmalloc: zero size");
  25. ptr = malloc(size);
  26. if (ptr == NULL)
  27. fatal("xmalloc: out of memory (allocating %lu bytes)", (u_long) size);
  28. return ptr;
  29. }
  30. void *
  31. xrealloc(void *ptr, size_t new_size)
  32. {
  33. void *new_ptr;
  34. if (new_size == 0)
  35. fatal("xrealloc: zero size");
  36. if (ptr == NULL)
  37. new_ptr = malloc(new_size);
  38. else
  39. new_ptr = realloc(ptr, new_size);
  40. if (new_ptr == NULL)
  41. fatal("xrealloc: out of memory (new_size %lu bytes)", (u_long) new_size);
  42. return new_ptr;
  43. }
  44. void
  45. xfree(void *ptr)
  46. {
  47. if (ptr == NULL)
  48. fatal("xfree: NULL pointer given as argument");
  49. free(ptr);
  50. }
  51. char
  52. *xstrdup(const char *str)
  53. {
  54. size_t len = strlen(str) + 1;
  55. char *cp;
  56. if (len == 0)
  57. fatal("xstrdup: zero size");
  58. cp = xmalloc(len);
  59. strlcpy(cp, str, len);
  60. return cp;
  61. }