snprintftest.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * Copyright (c) 2005 Darren Tucker
  3. * Copyright (c) 2005 Damien Miller
  4. *
  5. * Permission to use, copy, modify, and distribute this software for any
  6. * purpose with or without fee is hereby granted, provided that the above
  7. * copyright notice and this permission notice appear in all copies.
  8. *
  9. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  10. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  11. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  12. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  13. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  14. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  15. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  16. */
  17. #define BUFSZ 2048
  18. #include <sys/types.h>
  19. #include <stdlib.h>
  20. #include <stdio.h>
  21. #include <stdarg.h>
  22. #include <string.h>
  23. static int failed = 0;
  24. static void
  25. fail(const char *m)
  26. {
  27. fprintf(stderr, "snprintftest: %s\n", m);
  28. failed = 1;
  29. }
  30. int x_snprintf(char *str, size_t count, const char *fmt, ...)
  31. {
  32. size_t ret;
  33. va_list ap;
  34. va_start(ap, fmt);
  35. ret = vsnprintf(str, count, fmt, ap);
  36. va_end(ap);
  37. return ret;
  38. }
  39. int
  40. main(void)
  41. {
  42. char b[5];
  43. char *src = NULL;
  44. snprintf(b,5,"123456789");
  45. if (b[4] != '\0')
  46. fail("snprintf does not correctly terminate long strings");
  47. /* check for read overrun on unterminated string */
  48. if ((src = malloc(BUFSZ)) == NULL) {
  49. fail("malloc failed");
  50. } else {
  51. memset(src, 'a', BUFSZ);
  52. snprintf(b, sizeof(b), "%.*s", 1, src);
  53. if (strcmp(b, "a") != 0)
  54. fail("failed with length limit '%%.s'");
  55. }
  56. /* check that snprintf and vsnprintf return sane values */
  57. if (snprintf(b, 1, "%s %d", "hello", 12345) != 11)
  58. fail("snprintf does not return required length");
  59. if (x_snprintf(b, 1, "%s %d", "hello", 12345) != 11)
  60. fail("vsnprintf does not return required length");
  61. free(src);
  62. return failed;
  63. }