ssh has moved
[netbsd-mini2440.git] / crypto / dist / ssh / xmalloc.c
blob243abec725493c5fea0a2fec2a24c47bdb1baa81
1 /* $NetBSD$ */
2 /* $OpenBSD: xmalloc.c,v 1.27 2006/08/03 03:34:42 deraadt Exp $ */
3 /*
4 * Author: Tatu Ylonen <ylo@cs.hut.fi>
5 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * All rights reserved
7 * Versions of malloc and friends that check their results, and never return
8 * failure (they call fatal if they encounter an error).
10 * As far as I am concerned, the code I have written for this software
11 * can be used freely for any purpose. Any derived versions of this
12 * software must be clearly marked as such, and if the derived work is
13 * incompatible with the protocol description in the RFC file, it must be
14 * called by a name other than "ssh" or "Secure Shell".
17 #include "includes.h"
18 __RCSID("$NetBSD$");
19 #include <sys/param.h>
20 #include <stdarg.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
25 #include "xmalloc.h"
26 #include "log.h"
28 void *
29 xmalloc(size_t size)
31 void *ptr;
33 if (size == 0)
34 fatal("xmalloc: zero size");
35 ptr = malloc(size);
36 if (ptr == NULL)
37 fatal("xmalloc: out of memory (allocating %lu bytes)", (u_long) size);
38 return ptr;
41 void *
42 xcalloc(size_t nmemb, size_t size)
44 void *ptr;
46 if (size == 0 || nmemb == 0)
47 fatal("xcalloc: zero size");
48 if (SIZE_T_MAX / nmemb < size)
49 fatal("xcalloc: nmemb * size > SIZE_T_MAX");
50 ptr = calloc(nmemb, size);
51 if (ptr == NULL)
52 fatal("xcalloc: out of memory (allocating %lu bytes)",
53 (u_long)(size * nmemb));
54 return ptr;
57 void *
58 xrealloc(void *ptr, size_t nmemb, size_t size)
60 void *new_ptr;
61 size_t new_size = nmemb * size;
63 if (new_size == 0)
64 fatal("xrealloc: zero size");
65 if (SIZE_T_MAX / nmemb < size)
66 fatal("xrealloc: nmemb * size > SIZE_T_MAX");
67 if (ptr == NULL)
68 new_ptr = malloc(new_size);
69 else
70 new_ptr = realloc(ptr, new_size);
71 if (new_ptr == NULL)
72 fatal("xrealloc: out of memory (new_size %lu bytes)",
73 (u_long) new_size);
74 return new_ptr;
77 void
78 xfree(void *ptr)
80 if (ptr == NULL)
81 fatal("xfree: NULL pointer given as argument");
82 free(ptr);
85 char *
86 xstrdup(const char *str)
88 size_t len;
89 char *cp;
91 len = strlen(str) + 1;
92 cp = xmalloc(len);
93 strlcpy(cp, str, len);
94 return cp;
97 int
98 xasprintf(char **ret, const char *fmt, ...)
100 va_list ap;
101 int i;
103 va_start(ap, fmt);
104 i = vasprintf(ret, fmt, ap);
105 va_end(ap);
107 if (i < 0 || *ret == NULL)
108 fatal("xasprintf: could not allocate memory");
110 return (i);