summaryrefslogtreecommitdiff
path: root/lib/util/alloc.c
blob: 2d748a755c0bdb74299bbf2d495846b4a29108f6 (plain)
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
43
44
45
46
47
48
49
50
51
52
53
54
/* SPDX-License-Identifier: GPL-3.0-or-later */
/*
 * alloc.c
 *
 * Copyright (C) 2019 David Oberhollenzer <goliath@infraroot.at>
 */
#include "config.h"

#include "util.h"

#include <stddef.h>
#include <stdlib.h>
#include <errno.h>

void *alloc_flex(size_t base_size, size_t item_size, size_t nmemb)
{
	size_t size;

	if (SZ_MUL_OV(nmemb, item_size, &size)) {
		errno = EOVERFLOW;
		return NULL;
	}

	if (SZ_ADD_OV(base_size, size, &size)) {
		errno = EOVERFLOW;
		return NULL;
	}

	return calloc(1, size);
}

void *alloc_array(size_t item_size, size_t nmemb)
{
	size_t size;

	if (SZ_MUL_OV(nmemb, item_size, &size)) {
		errno = EOVERFLOW;
		return NULL;
	}

	return calloc(1, size);
}

void *alloc_string(size_t len)
{
	size_t size;

	if (SZ_ADD_OV(len, 1, &size)) {
		errno = EOVERFLOW;
		return NULL;
	}

	return calloc(1, len);
}