File: imalloc.h

package info (click to toggle)
spiped 1.6.4-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,328 kB
  • sloc: ansic: 11,951; sh: 1,081; makefile: 629; perl: 121
file content (42 lines) | stat: -rw-r--r-- 903 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#ifndef IMALLOC_H_
#define IMALLOC_H_

#include <assert.h>
#include <errno.h>
#include <stdint.h>
#include <stdlib.h>

/**
 * imalloc(nrec, reclen):
 * Allocate ${nrec} records of length ${reclen}.  Check for size_t overflow.
 * ${reclen} must not be zero.  If ${nrec} is zero, return NULL.
 */
static inline void *
imalloc(size_t nrec, size_t reclen)
{

	/* Sanity check. */
	assert(reclen != 0);

	/* Handle cases where we don't allocate memory. */
	if (nrec == 0)
		return (NULL);
	if (nrec > SIZE_MAX / reclen) {
		errno = ENOMEM;
		return (NULL);
	}

	/* Allocate memory. */
	return (malloc(nrec * reclen));
}

/**
 * IMALLOC(p, nrec, type):
 * Allocate ${nrec} records of type ${type} and store the pointer in ${p}.
 * Return non-zero on failure.
 */
#define IMALLOC(p, nrec, type)						\
	((((p) = (type *)imalloc((nrec), sizeof(type))) == NULL) &&	\
	    ((nrec) > 0))

#endif /* !IMALLOC_H_ */