1 /* Test of POSIX compatible fprintf() function.
2 Copyright (C) 2009, 2010 Free Software Foundation, Inc.
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.
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.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
17 /* Written by Bruno Haible <bruno@clisp.org>, 2009. */
23 #if HAVE_GETRLIMIT && HAVE_SETRLIMIT
26 #include <sys/types.h>
28 #include <sys/resource.h>
32 /* Test against a memory leak in the fprintf replacement. */
34 /* Number of iterations across the loop. */
35 #define NUM_ROUNDS 1000
37 /* Number of bytes that are allowed to escape per round. */
38 #define MAX_ALLOC_ROUND 10000
40 /* Number of bytes that are allowed to escape in total.
41 This should be at least 10 MB, since it includes the normal memory
42 or address space of the test program. */
43 #define MAX_ALLOC_TOTAL (NUM_ROUNDS * MAX_ALLOC_ROUND)
46 main (int argc, char *argv[])
52 /* Limit the amount of malloc()ed memory to MAX_ALLOC_TOTAL or less. */
54 /* On BSD systems, malloc() is limited by RLIMIT_DATA. */
56 if (getrlimit (RLIMIT_DATA, &limit) < 0)
58 if (limit.rlim_max == RLIM_INFINITY || limit.rlim_max > MAX_ALLOC_TOTAL)
59 limit.rlim_max = MAX_ALLOC_TOTAL;
60 limit.rlim_cur = limit.rlim_max;
61 if (setrlimit (RLIMIT_DATA, &limit) < 0)
64 /* On Linux systems, malloc() is limited by RLIMIT_AS. */
66 if (getrlimit (RLIMIT_AS, &limit) < 0)
68 if (limit.rlim_max == RLIM_INFINITY || limit.rlim_max > MAX_ALLOC_TOTAL)
69 limit.rlim_max = MAX_ALLOC_TOTAL;
70 limit.rlim_cur = limit.rlim_max;
71 if (setrlimit (RLIMIT_AS, &limit) < 0)
78 void *memory = malloc (MAX_ALLOC_TOTAL);
81 memset (memory, 17, MAX_ALLOC_TOTAL);
85 /* Perform the test and test whether it triggers a permanent memory
86 allocation of more than MAX_ALLOC_TOTAL bytes. */
88 for (repeat = 0; repeat < NUM_ROUNDS; repeat++)
90 /* This may produce a temporary memory allocation of 11000 bytes.
91 but should not result in a permanent memory allocation. */
92 if (fprintf (stdout, "%011000d\n", 17) == -1
103 main (int argc, char *argv[])