mallocbug.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /* Reproduce a GNU malloc bug. */
  2. #include <malloc.h>
  3. #include <stdio.h>
  4. #include <string.h>
  5. #define size_t unsigned int
  6. /* Defined as global variables to avoid warnings about unused variables. */
  7. char *dummy0;
  8. char *dummy1;
  9. char *fill_info_table1;
  10. int
  11. main (int argc, char *argv[])
  12. {
  13. char *over_top;
  14. size_t over_top_size = 0x3000;
  15. char *over_top_dup;
  16. size_t over_top_dup_size = 0x7000;
  17. char *x;
  18. size_t i;
  19. /* Here's what memory is supposed to look like (hex):
  20. size contents
  21. 3000 original_info_table, later fill_info_table1
  22. 3fa000 dummy0
  23. 3fa000 dummy1
  24. 6000 info_table_2
  25. 3000 over_top
  26. */
  27. /* mem: original_info_table */
  28. dummy0 = malloc (0x3fa000);
  29. /* mem: original_info_table, dummy0 */
  30. dummy1 = malloc (0x3fa000);
  31. /* mem: free, dummy0, dummy1, info_table_2 */
  32. fill_info_table1 = malloc (0x3000);
  33. /* mem: fill_info_table1, dummy0, dummy1, info_table_2 */
  34. x = malloc (0x1000);
  35. free (x);
  36. /* mem: fill_info_table1, dummy0, dummy1, info_table_2, freexx */
  37. /* This is what loses; info_table_2 and freexx get combined unbeknownst
  38. to mmalloc, and mmalloc puts over_top in a section of memory which
  39. is on the free list as part of another block (where info_table_2 had
  40. been). */
  41. over_top = malloc (over_top_size);
  42. over_top_dup = malloc (over_top_dup_size);
  43. memset (over_top, 0, over_top_size);
  44. memset (over_top_dup, 1, over_top_dup_size);
  45. for (i = 0; i < over_top_size; ++i)
  46. if (over_top[i] != 0)
  47. {
  48. printf ("FAIL: malloc expands info table\n");
  49. return 0;
  50. }
  51. for (i = 0; i < over_top_dup_size; ++i)
  52. if (over_top_dup[i] != 1)
  53. {
  54. printf ("FAIL: malloc expands info table\n");
  55. return 0;
  56. }
  57. printf ("PASS: malloc expands info table\n");
  58. return 0;
  59. }