xmalloc.c 1.7 KB

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