mallocbug.c 1.7 KB

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