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

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