free.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /* Make free() preserve errno.
  2. Copyright (C) 2003, 2006, 2009-2021 Free Software Foundation, Inc.
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Lesser General Public License as published by
  5. the Free Software Foundation; either version 3 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Lesser General Public License for more details.
  11. You should have received a copy of the GNU Lesser General Public License
  12. along with this program. If not, see <https://www.gnu.org/licenses/>. */
  13. /* written by Paul Eggert */
  14. #include <config.h>
  15. /* Specification. */
  16. #include <stdlib.h>
  17. /* A function definition is only needed if HAVE_FREE_POSIX is not defined. */
  18. #if !HAVE_FREE_POSIX
  19. # include <errno.h>
  20. void
  21. rpl_free (void *p)
  22. # undef free
  23. {
  24. # if defined __GNUC__ && !defined __clang__
  25. /* An invalid GCC optimization
  26. <https://gcc.gnu.org/bugzilla/show_bug.cgi?id=98396>
  27. would optimize away the assignments in the code below, when link-time
  28. optimization (LTO) is enabled. Make the code more complicated, so that
  29. GCC does not grok how to optimize it. */
  30. int err[2];
  31. err[0] = errno;
  32. err[1] = errno;
  33. errno = 0;
  34. free (p);
  35. errno = err[errno == 0];
  36. # else
  37. int err = errno;
  38. free (p);
  39. errno = err;
  40. # endif
  41. }
  42. #endif