1 /* Test for reallocarray.
2 Copyright (C) 2017-2022 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
10 The GNU C Library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, see
17 <https://www.gnu.org/licenses/>. */
22 #include <support/check.h>
23 #include <libc-diag.h>
26 reallocarray_nowarn (void *ptr
, size_t nmemb
, size_t size
)
28 #if __GNUC_PREREQ (7, 0)
29 /* GCC 7 warns about too-large allocations; here we want to test
31 DIAG_IGNORE_NEEDS_COMMENT (7, "-Walloc-size-larger-than=");
33 void *ret
= reallocarray (ptr
, nmemb
, size
);
34 #if __GNUC_PREREQ (7, 0)
35 DIAG_POP_NEEDS_COMMENT
;
49 const size_t max
= ~(size_t)0;
52 /* Test overflow detection. */
54 ptr
= reallocarray_nowarn (NULL
, max
, 2);
56 TEST_VERIFY (errno
== ENOMEM
);
59 ptr
= reallocarray_nowarn (NULL
, 2, max
);
61 TEST_VERIFY (errno
== ENOMEM
);
66 ptr
= reallocarray_nowarn (NULL
, a
, b
);
68 TEST_VERIFY (errno
== ENOMEM
);
71 ptr
= reallocarray_nowarn (NULL
, b
, a
);
73 TEST_VERIFY (errno
== ENOMEM
);
75 /* Test realloc-like behavior. */
76 /* Allocate memory like malloc. */
77 ptr
= reallocarray (NULL
, 10, 2);
78 TEST_VERIFY_EXIT (ptr
);
79 TEST_VERIFY_EXIT (malloc_usable_size (ptr
) >= 10*2);
81 memset (ptr
, 0xAF, 10*2);
84 ptr2
= reallocarray (ptr
, 20, 2);
88 TEST_VERIFY (malloc_usable_size (ptr
) >= 20*2);
92 for (i
= 0; i
< 10*2; ++i
)
99 /* Decrease buffer size. */
100 ptr2
= reallocarray (ptr
, 5, 3);
104 TEST_VERIFY_EXIT (malloc_usable_size (ptr
) >= 5*3);
108 for (i
= 0; i
< 5*3; ++i
)
115 /* Overflow should leave buffer untouched. */
117 ptr2
= reallocarray_nowarn (ptr
, 2, ~(size_t)0);
119 TEST_VERIFY (errno
== ENOMEM
);
123 for (i
= 0; i
< 5*3; ++i
)
135 #include <support/test-driver.c>