| 1 | // SPDX-License-Identifier: GPL-3.0-or-later |
| 2 | /* xmalloc.c -- malloc with out of memory checking |
| 3 | * |
| 4 | * Copyright (C) 1990-2000, 2002-2006, 2008-2012 Free Software Foundation, Inc. |
| 5 | * |
| 6 | * This program is free software: you can redistribute it and/or modify |
| 7 | * it under the terms of the GNU General Public License as published by |
| 8 | * the Free Software Foundation; either version 3 of the License, or |
| 9 | * (at your option) any later version. |
| 10 | * |
| 11 | * This program is distributed in the hope that it will be useful, |
| 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 14 | * GNU General Public License for more details. |
| 15 | * |
| 16 | * You should have received a copy of the GNU General Public License |
| 17 | * along with this program. If not, see <http://www.gnu.org/licenses/>. */ |
| 18 | |
| 19 | #include <errno.h> |
| 20 | #include <stdio.h> |
| 21 | #include <stdlib.h> |
| 22 | #include <string.h> |
| 23 | |
| 24 | # include "messages.h" |
| 25 | # include "xalloc.h" |
| 26 | |
| 27 | /* Allocate N bytes of memory dynamically, with error checking. |
| 28 | * The memory is set to zero. */ |
| 29 | |
| 30 | void * |
| 31 | xmalloc (const size_t n) |
| 32 | { |
| 33 | void *p = calloc (1, n); |
| 34 | if (!p && n != 0) |
| 35 | plugin_error (STATE_UNKNOWN, errno, "memory exhausted"); |
| 36 | return p; |
| 37 | } |
| 38 | |
| 39 | /* Clone an object P of size S, with error checking. There's no need |
| 40 | * for xnmemdup (P, N, S), since xmemdup (P, N * S) works without any |
| 41 | * need for an arithmetic overflow check. */ |
| 42 | |
| 43 | void * |
| 44 | xmemdup (void const *p, const size_t s) |
| 45 | { |
| 46 | return memcpy (xmalloc (s), p, s); |
| 47 | } |
| 48 | |
| 49 | /* Clone STRING. */ |
| 50 | |
| 51 | char * |
| 52 | xstrdup (char const *string) |
| 53 | { |
| 54 | return xmemdup (string, strlen (string) + 1); |
| 55 | } |
| 56 | |
| 57 | /* Clone a substring of lenght S, starting at the address START. |
| 58 | * S characters will be copied into the new allocated memory and |
| 59 | * a null character will be added at the and. */ |
| 60 | |
| 61 | char * |
| 62 | xsubstrdup (char const *start, const size_t s) |
| 63 | { |
| 64 | return memcpy (xmalloc (s + 1), start, s); |
| 65 | } |
| 66 | |
| 67 | /* Allocate an array of N objects, each with S bytes of memory, |
| 68 | * dynamically, with error checking. S must be nonzero. */ |
| 69 | |
| 70 | void * |
| 71 | xnmalloc (const size_t n, const size_t s) |
| 72 | { |
| 73 | return xmalloc (n * s); |
| 74 | } |
| 75 | |
| 76 | /* Memory allocation wrapper for realloc */ |
| 77 | |
| 78 | void * |
| 79 | xrealloc (void *ptr, const size_t size) |
| 80 | { |
| 81 | void *ret = realloc (ptr, size); |
| 82 | if (!ret && size) |
| 83 | plugin_error (STATE_UNKNOWN, errno, "memory exhausted"); |
| 84 | return ret; |
| 85 | } |