tst-malloc.c 2.3 KB

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