Update copyright notices with scripts/update-copyrights
[glibc.git] / malloc / tst-calloc.c
blob51e6c25ebf73c9482ebdae37687cc5f7c75051e3
1 /* Copyright (C) 2000-2014 Free Software Foundation, Inc.
2 This file is part of the GNU C Library.
3 Contributed by Ulrich Drepper <drepper@redhat.com>.
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 <error.h>
21 #include <limits.h>
22 #include <malloc.h>
23 #include <stdlib.h>
24 #include <stdio.h>
27 /* Number of samples per size. */
28 #define N 50000
31 static void
32 fixed_test (int size)
34 char *ptrs[N];
35 int i;
37 for (i = 0; i < N; ++i)
39 int j;
41 ptrs[i] = (char *) calloc (1, size);
43 if (ptrs[i] == NULL)
44 break;
46 for (j = 0; j < size; ++j)
48 if (ptrs[i][j] != '\0')
49 error (EXIT_FAILURE, 0,
50 "byte not cleared (size %d, element %d, byte %d)",
51 size, i, j);
52 ptrs[i][j] = '\xff';
56 while (i-- > 0)
57 free (ptrs[i]);
61 static void
62 random_test (void)
64 char *ptrs[N];
65 int i;
67 for (i = 0; i < N; ++i)
69 int j;
70 int n = 1 + random () % 10;
71 int elem = 1 + random () % 100;
72 int size = n * elem;
74 ptrs[i] = (char *) calloc (n, elem);
76 if (ptrs[i] == NULL)
77 break;
79 for (j = 0; j < size; ++j)
81 if (ptrs[i][j] != '\0')
82 error (EXIT_FAILURE, 0,
83 "byte not cleared (size %d, element %d, byte %d)",
84 size, i, j);
85 ptrs[i][j] = '\xff';
89 while (i-- > 0)
90 free (ptrs[i]);
94 static void
95 null_test (void)
97 /* If the size is 0 the result is implementation defined. Just make
98 sure the program doesn't crash. */
99 calloc (0, 0);
100 calloc (0, UINT_MAX);
101 calloc (UINT_MAX, 0);
102 calloc (0, ~((size_t) 0));
103 calloc (~((size_t) 0), 0);
108 main (void)
110 /* We are allocating blocks with `calloc' and check whether every
111 block is completely cleared. We first try this for some fixed
112 times and then with random size. */
113 fixed_test (15);
114 fixed_test (5);
115 fixed_test (17);
116 fixed_test (6);
117 fixed_test (31);
118 fixed_test (96);
120 random_test ();
122 null_test ();
124 return 0;