PageRenderTime 51ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/mexwrapper/strlcpy.c

https://bitbucket.org/BlairJamieson/midas-blairjamieson
C | 82 lines | 43 code | 11 blank | 28 comment | 23 complexity | 972f1e5d267ae606c925bfde1474b80b MD5 | raw file
Possible License(s): GPL-2.0
  1. /********************************************************************\
  2. Name: strlcpy.c
  3. Created by: Stefan Ritt
  4. Contents: Contains strlcpy and strlcat which are versions of
  5. strcpy and strcat, but which avoid buffer overflows
  6. $Id: strlcpy.c 16 2005-10-07 13:05:38Z ritt $
  7. \********************************************************************/
  8. #include <stdio.h>
  9. #include <string.h>
  10. #include "strlcpy.h"
  11. /*
  12. * Copy src to string dst of size siz. At most siz-1 characters
  13. * will be copied. Always NUL terminates (unless size == 0).
  14. * Returns strlen(src); if retval >= siz, truncation occurred.
  15. */
  16. size_t strlcpy(char *dst, const char *src, size_t size)
  17. {
  18. char *d = dst;
  19. const char *s = src;
  20. size_t n = size;
  21. /* Copy as many bytes as will fit */
  22. if (n != 0 && --n != 0) {
  23. do {
  24. if ((*d++ = *s++) == 0)
  25. break;
  26. } while (--n != 0);
  27. }
  28. /* Not enough room in dst, add NUL and traverse rest of src */
  29. if (n == 0) {
  30. if (size != 0)
  31. *d = '\0'; /* NUL-terminate dst */
  32. while (*s++);
  33. }
  34. return (s - src - 1); /* count does not include NUL */
  35. }
  36. /*-------------------------------------------------------------------*/
  37. /*
  38. * Appends src to string dst of size siz (unlike strncat, siz is the
  39. * full size of dst, not space left). At most siz-1 characters
  40. * will be copied. Always NUL terminates (unless size <= strlen(dst)).
  41. * Returns strlen(src) + MIN(size, strlen(initial dst)).
  42. * If retval >= size, truncation occurred.
  43. */
  44. size_t strlcat(char *dst, const char *src, size_t size)
  45. {
  46. char *d = dst;
  47. const char *s = src;
  48. size_t n = size;
  49. size_t dlen;
  50. /* Find the end of dst and adjust bytes left but don't go past end */
  51. while (n-- != 0 && *d != '\0')
  52. d++;
  53. dlen = d - dst;
  54. n = size - dlen;
  55. if (n == 0)
  56. return (dlen + strlen(s));
  57. while (*s != '\0') {
  58. if (n != 1) {
  59. *d++ = *s;
  60. n--;
  61. }
  62. s++;
  63. }
  64. *d = '\0';
  65. return (dlen + (s - src)); /* count does not include NUL */
  66. }
  67. /*-------------------------------------------------------------------*/