04
Dec
Safe String Copy(strcpy) and Concatenate(strcat) Operations
Related Blog Items
- Bad Standard APIs
- C++ Basics Tutorial - Lesson 4
- const correctness
- Differences between new, malloc; delete, free
- i64toa - Converts a 64 bit integer to string
I’d covered bad standard APIs in my previous article, here I’ve attempted to overcome those defects in standard APIs, please check these fucntions.. I’ll post more functions later..
Strcpy:
1)copy src to string dst of size size
2)At most size-1 characters will be copied
3)Returns strlen(src); if retval >= size, truncation occurred
4)Always NUL terminates (unless size is 0)
size_t safe_strcpy(char *dst, const char *src, size_t size)
{
const char *s = src;
size_t n = size;
if (size != 0)
{
while (--size != 0)
{
if ((*dst++ = *src++) == 0)
break;
}
}
if (size == 0)
{
if (n)
*dst = 0;
while (*src++);
}
//count does not include ''
return(src-s-1);
}
strcat:
1)Appends src to string dst of size size, unlike strncat size is the full size of dst
2)At most size-1 characters will be copied
3)Always NUL terminates (unless size = siz, truncation occurred.
size_t safe_strcat(char *dst, const char *src, size_t size) { char *d = dst; const char *s = src; size_t n = size; size_t dstlen; while (n-- != 0 && *d != 0) { d++; } dstlen = d - dst; n = size - dstlen; if (n == 0) { return(dstlen + strlen(s)); } while (*s != 0) { if (n != 1) { *d++ = *s; n--; } s++; } *d = 0; return(dstlen + (s - src)); }
download src safe string operations
Popularity: 8%
You need to log on to convert this article into PDF
Related Blog Items - Bad Standard APIs
- C++ Basics Tutorial - Lesson 4
- const correctness
- Differences between new, malloc; delete, free
- i64toa - Converts a 64 bit integer to string
Related Blog Items
- Bad Standard APIs
- C++ Basics Tutorial - Lesson 4
- const correctness
- Differences between new, malloc; delete, free
- i64toa - Converts a 64 bit integer to string
No Comments
No comments yet.