Add sysdeps/ieee754/soft-fp.
[glibc.git] / malloc / tst-reallocarray.c
blobf1cbf7fe0addb8c366cb31686b82c8e0c5dd4852
1 /* Test for reallocarray.
2 Copyright (C) 2017 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 <http://www.gnu.org/licenses/>. */
19 #include <errno.h>
20 #include <malloc.h>
21 #include <string.h>
22 #include <support/check.h>
24 static int
25 do_test (void)
27 void *ptr = NULL;
28 void *ptr2 = NULL;
29 unsigned char *c;
30 size_t i;
31 int ok;
32 const size_t max = ~(size_t)0;
33 size_t a, b;
35 /* Test overflow detection. */
36 errno = 0;
37 ptr = reallocarray (NULL, max, 2);
38 TEST_VERIFY (!ptr);
39 TEST_VERIFY (errno == ENOMEM);
41 errno = 0;
42 ptr = reallocarray (NULL, 2, max);
43 TEST_VERIFY (!ptr);
44 TEST_VERIFY (errno == ENOMEM);
46 a = 65537;
47 b = max/65537 + 1;
48 errno = 0;
49 ptr = reallocarray (NULL, a, b);
50 TEST_VERIFY (!ptr);
51 TEST_VERIFY (errno == ENOMEM);
53 errno = 0;
54 ptr = reallocarray (NULL, b, a);
55 TEST_VERIFY (!ptr);
56 TEST_VERIFY (errno == ENOMEM);
58 /* Test realloc-like behavior. */
59 /* Allocate memory like malloc. */
60 ptr = reallocarray (NULL, 10, 2);
61 TEST_VERIFY_EXIT (ptr);
62 TEST_VERIFY_EXIT (malloc_usable_size (ptr) >= 10*2);
64 memset (ptr, 0xAF, 10*2);
66 /* Enlarge buffer. */
67 ptr2 = reallocarray (ptr, 20, 2);
68 TEST_VERIFY (ptr2);
69 if (ptr2)
70 ptr = ptr2;
71 TEST_VERIFY (malloc_usable_size (ptr) >= 20*2);
73 c = ptr;
74 ok = 1;
75 for (i = 0; i < 10*2; ++i)
77 if (c[i] != 0xAF)
78 ok = 0;
80 TEST_VERIFY (ok);
82 /* Decrease buffer size. */
83 ptr2 = reallocarray (ptr, 5, 3);
84 TEST_VERIFY (ptr2);
85 if (ptr2)
86 ptr = ptr2;
87 TEST_VERIFY_EXIT (malloc_usable_size (ptr) >= 5*3);
89 c = ptr;
90 ok = 1;
91 for (i = 0; i < 5*3; ++i)
93 if (c[i] != 0xAF)
94 ok = 0;
96 TEST_VERIFY (ok);
98 /* Overflow should leave buffer untouched. */
99 errno = 0;
100 ptr2 = reallocarray (ptr, 2, ~(size_t)0);
101 TEST_VERIFY (!ptr2);
102 TEST_VERIFY (errno == ENOMEM);
104 c = ptr;
105 ok = 1;
106 for (i = 0; i < 5*3; ++i)
108 if (c[i] != 0xAF)
109 ok = 0;
111 TEST_VERIFY (ok);
113 free (ptr);
115 return 0;
118 #include <support/test-driver.c>