tst-tcfree3.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /* Test that malloc tcache catches double free.
  2. Copyright (C) 2018-2026 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  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. The GNU C Library is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public
  13. License along with the GNU C Library; if not, see
  14. <https://www.gnu.org/licenses/>. */
  15. #include <malloc.h>
  16. #include <string.h>
  17. static int
  18. do_test (void)
  19. {
  20. /* Do two allocation of any size that fit in tcache, and one that
  21. doesn't. */
  22. int ** volatile a = malloc (32);
  23. int ** volatile b = malloc (32);
  24. /* This is just under the mmap threshold. */
  25. int ** volatile c = malloc (127 * 1024);
  26. /* The invalid "tcache bucket" we might dereference will likely end
  27. up somewhere within this memory block, so make all the accidental
  28. "next" pointers cause segfaults. BZ #23907. */
  29. memset (c, 0xff, 127 * 1024);
  30. free (a); // puts in tcache
  31. /* A is now free and contains the key we use to detect in-tcache.
  32. Copy the key to the other chunks. */
  33. memcpy (b, a, 32);
  34. memcpy (c, a, 32);
  35. /* This free tests the "are we in the tcache already" loop with a
  36. VALID bin but "coincidental" matching key. */
  37. free (b); // should NOT abort
  38. /* This free tests the "is it a valid tcache bin" test. */
  39. free (c); // should NOT abort
  40. return 0;
  41. }
  42. #include <support/test-driver.c>