bug-memstream1.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4. static int
  5. do_test (void)
  6. {
  7. size_t size;
  8. char *buf;
  9. FILE *fp = open_memstream (&buf, &size);
  10. if (fp == NULL)
  11. {
  12. puts ("open_memstream failed");
  13. return 1;
  14. }
  15. off64_t off = ftello64 (fp);
  16. if (off != 0)
  17. {
  18. puts ("initial position wrong");
  19. return 1;
  20. }
  21. if (fseek (fp, 32768, SEEK_SET) != 0)
  22. {
  23. puts ("fseek failed");
  24. return 1;
  25. }
  26. if (fputs ("foo", fp) == EOF)
  27. {
  28. puts ("fputs failed");
  29. return 1;
  30. }
  31. if (fclose (fp) == EOF)
  32. {
  33. puts ("fclose failed");
  34. return 1;
  35. }
  36. if (size != 32768 + 3)
  37. {
  38. printf ("expected size %d, got %zu\n", 32768 + 3, size);
  39. return 1;
  40. }
  41. for (int i = 0; i < 32768; ++i)
  42. if (buf[i] != '\0')
  43. {
  44. printf ("byte at offset %d is %#hhx\n", i, buf[i]);
  45. return 1;
  46. }
  47. if (memcmp (buf + 32768, "foo", 3) != 0)
  48. {
  49. puts ("written string incorrect");
  50. return 1;
  51. }
  52. /* Mark the buffer. */
  53. memset (buf, 'A', size);
  54. free (buf);
  55. /* Try again, this time with write mode enabled before the seek. */
  56. fp = open_memstream (&buf, &size);
  57. if (fp == NULL)
  58. {
  59. puts ("2nd open_memstream failed");
  60. return 1;
  61. }
  62. off = ftello64 (fp);
  63. if (off != 0)
  64. {
  65. puts ("2nd initial position wrong");
  66. return 1;
  67. }
  68. if (fputs ("bar", fp) == EOF)
  69. {
  70. puts ("2nd fputs failed");
  71. return 1;
  72. }
  73. if (fseek (fp, 32768, SEEK_SET) != 0)
  74. {
  75. puts ("2nd fseek failed");
  76. return 1;
  77. }
  78. if (fputs ("foo", fp) == EOF)
  79. {
  80. puts ("3rd fputs failed");
  81. return 1;
  82. }
  83. if (fclose (fp) == EOF)
  84. {
  85. puts ("2nd fclose failed");
  86. return 1;
  87. }
  88. if (size != 32768 + 3)
  89. {
  90. printf ("2nd expected size %d, got %zu\n", 32768 + 3, size);
  91. return 1;
  92. }
  93. if (memcmp (buf, "bar", 3) != 0)
  94. {
  95. puts ("initial string incorrect in 2nd try");
  96. return 1;
  97. }
  98. for (int i = 3; i < 32768; ++i)
  99. if (buf[i] != '\0')
  100. {
  101. printf ("byte at offset %d is %#hhx in 2nd try\n", i, buf[i]);
  102. return 1;
  103. }
  104. if (memcmp (buf + 32768, "foo", 3) != 0)
  105. {
  106. puts ("written string incorrect in 2nd try");
  107. return 1;
  108. }
  109. return 0;
  110. }
  111. #define TEST_FUNCTION do_test ()
  112. #include "../test-skeleton.c"