1/* Copyright (C) 1999-2024 Free Software Foundation, Inc.
2 This file is part of the GNU C Library.
3
4 The GNU C Library is free software; you can redistribute it and/or
5 modify it under the terms of the GNU Lesser General Public
6 License as published by the Free Software Foundation; either
7 version 2.1 of the License, or (at your option) any later version.
8
9 The GNU C Library 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 GNU
12 Lesser General Public License for more details.
13
14 You should have received a copy of the GNU Lesser General Public
15 License along with the GNU C Library; if not, see
16 <https://www.gnu.org/licenses/>. */
17
18#include <errno.h>
19#include <malloc.h>
20#include <stdio.h>
21#include <stdlib.h>
22#include <libc-diag.h>
23#include <time.h>
24
25#include "tst-malloc-aux.h"
26
27static int errors = 0;
28
29static void
30merror (const char *msg)
31{
32 ++errors;
33 printf (format: "Error: %s\n", msg);
34}
35
36static int
37do_test (void)
38{
39 void *p, *q;
40 int save;
41
42 srandom (seed: time (NULL));
43
44 errno = 0;
45
46 DIAG_PUSH_NEEDS_COMMENT;
47#if __GNUC_PREREQ (7, 0)
48 /* GCC 7 warns about too-large allocations; here we want to test
49 that they fail. */
50 DIAG_IGNORE_NEEDS_COMMENT (7, "-Walloc-size-larger-than=");
51#endif
52 p = malloc (-1);
53 DIAG_POP_NEEDS_COMMENT;
54 save = errno;
55
56 if (p != NULL)
57 merror (msg: "malloc (-1) succeeded.");
58
59 if (p == NULL && save != ENOMEM)
60 merror (msg: "errno is not set correctly");
61
62 p = malloc (10);
63 if (p == NULL)
64 merror (msg: "malloc (10) failed.");
65
66 /* realloc (p, 0) == free (p). */
67 p = realloc (p, 0);
68 if (p != NULL)
69 merror (msg: "realloc (p, 0) failed.");
70
71 p = malloc (0);
72 if (p == NULL)
73 merror (msg: "malloc (0) failed.");
74
75 p = realloc (p, 0);
76 if (p != NULL)
77 merror (msg: "realloc (p, 0) failed.");
78
79 p = malloc (513 * 1024);
80 if (p == NULL)
81 merror (msg: "malloc (513K) failed.");
82
83 DIAG_PUSH_NEEDS_COMMENT;
84#if __GNUC_PREREQ (7, 0)
85 /* GCC 7 warns about too-large allocations; here we want to test
86 that they fail. */
87 DIAG_IGNORE_NEEDS_COMMENT (7, "-Walloc-size-larger-than=");
88#endif
89 q = malloc (-512 * 1024);
90 DIAG_POP_NEEDS_COMMENT;
91 if (q != NULL)
92 merror (msg: "malloc (-512K) succeeded.");
93
94 free (ptr: p);
95
96 return errors != 0;
97}
98
99#define TEST_FUNCTION do_test ()
100#include "../test-skeleton.c"
101

source code of glibc/malloc/tst-malloc.c