code_junkie

What size should I allow for strerror_r?

Nov 13th, 2011
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.19 KB | None | 0 0
  1. int result = gethostname(p_buffy, size_buffy);
  2. int errsv = errno;
  3. if (result < 0)
  4. {
  5. char buf[256];
  6. char const * str = strerror_r(errsv, buf, 256);
  7. syslog(LOG_ERR,
  8. "gethostname failed; errno=%d(%s), buf='%s'",
  9. errsv,
  10. str,
  11. p_buffy);
  12. return errsv;
  13. }
  14.  
  15. char *
  16. strerror (errnum)
  17. int errnum;
  18. {
  19. ...
  20. buf = malloc (1024);
  21.  
  22. #include <errno.h>
  23. #include <stdio.h>
  24. #include <stdlib.h>
  25. #include <string.h>
  26.  
  27. /* Call strerror_r and get the full error message. Allocate memory for the
  28. * entire string with malloc. Return string. Caller must free string.
  29. * If malloc fails, return NULL.
  30. */
  31. char *all_strerror(int n)
  32. {
  33. char *s;
  34. size_t size;
  35.  
  36. size = 1024;
  37. s = malloc(size);
  38. if (s == NULL)
  39. return NULL;
  40.  
  41. while (strerror_r(n, s, size) == -1 && errno == ERANGE) {
  42. size += 2;
  43. s = realloc(s, size);
  44. if (s == NULL)
  45. return NULL;
  46. }
  47.  
  48. return s;
  49. }
  50.  
  51. int main(int argc, char **argv)
  52. {
  53. for (int i = 1; i < argc; ++i) {
  54. int n = atoi(argv[i]);
  55. char *s = all_strerror(n);
  56. printf("[%d]: %sn", n, s);
  57. free(s);
  58. }
  59.  
  60. return 0;
  61. }
Add Comment
Please, Sign In to add comment