Debian Codegraph @

gnulib-tests/test-realloc-posix.c

raw
1 /* Test of realloc function.
2 Copyright (C) 2010-2025 Free Software Foundation, Inc.
3
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <https://www.gnu.org/licenses/>. */
16
17 #include <config.h>
18
19 /* Specification. */
20 #include <stdlib.h>
21
22 #include <errno.h>
23 #include <stdint.h>
24
25 #include "macros.h"
26
27 /* Work around clang bug
28 <https://github.com/llvm/llvm-project/issues/114772>. */
29 void *(*volatile my_realloc) (void *, size_t) = realloc;
30 #undef realloc
31 #define realloc my_realloc
32
33 int
34 main (int argc, _GL_UNUSED char **argv)
35 {
36 void *p;
37
38 /* Check that realloc (NULL, 0) is not a NULL pointer. */
39 p = realloc (NULL, 0);
40 ASSERT (p != NULL);
41 #ifdef NOT_YET
42 free (p);
43
44 /* Check that realloc (p, 0) for non-NULL p is not a NULL pointer. */
45 p = malloc (200);
46 p = realloc (p, 0);
47 ASSERT (p != NULL);
48 free (p);
49
50 /* Check that realloc (p, 0) for non-NULL p is not a NULL pointer. */
51 p = malloc (2 * 1024 * 1024);
52 p = realloc (p, 0);
53 ASSERT (p != NULL);
54 #endif
55
56 /* Check that realloc (p, n) fails when p is non-null and n exceeds
57 PTRDIFF_MAX. */
58 if (PTRDIFF_MAX < SIZE_MAX)
59 {
60 size_t one = argc != 12345;
61 void *r = realloc (p, PTRDIFF_MAX + one);
62 ASSERT (r == NULL);
63 /* Avoid a test failure due to glibc bug
64 <https://sourceware.org/bugzilla/show_bug.cgi?id=27870>. */
65 if (!getenv ("MALLOC_CHECK_"))
66 ASSERT (errno == ENOMEM);
67 }
68
69 /* Check that realloc sets errno when it fails.
70 Do this only in 64-bit processes, because there are many bi-arch systems
71 nowadays where a 32-bit process can actually allocate 2 GiB of RAM. */
72 if (sizeof (size_t) >= 8)
73 {
74 void *r;
75
76 errno = 0;
77 r = realloc (p, SIZE_MAX / 10);
78 ASSERT (r == NULL);
79 ASSERT (errno == ENOMEM);
80
81 errno = 0;
82 r = realloc (p, SIZE_MAX / 3);
83 ASSERT (r == NULL);
84 ASSERT (errno == ENOMEM);
85 }
86
87 free (p);
88 return test_exit_status;
89 }