1/* Test that malloc tcache catches double free.
2 Copyright (C) 2018-2024 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4
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.
9
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.
14
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/>. */
18
19#include <malloc.h>
20#include <string.h>
21
22static int
23do_test (void)
24{
25 /* Do two allocation of any size that fit in tcache, and one that
26 doesn't. */
27 int ** volatile a = malloc (size: 32);
28 int ** volatile b = malloc (size: 32);
29 /* This is just under the mmap threshold. */
30 int ** volatile c = malloc (size: 127 * 1024);
31
32 /* The invalid "tcache bucket" we might dereference will likely end
33 up somewhere within this memory block, so make all the accidental
34 "next" pointers cause segfaults. BZ #23907. */
35 memset (c, 0xff, 127 * 1024);
36
37 free (ptr: a); // puts in tcache
38
39 /* A is now free and contains the key we use to detect in-tcache.
40 Copy the key to the other chunks. */
41 memcpy (b, a, 32);
42 memcpy (c, a, 32);
43
44 /* This free tests the "are we in the tcache already" loop with a
45 VALID bin but "coincidental" matching key. */
46 free (ptr: b); // should NOT abort
47 /* This free tests the "is it a valid tcache bin" test. */
48 free (ptr: c); // should NOT abort
49
50 return 0;
51}
52
53#include <support/test-driver.c>
54

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