Write versions of the library functions
strncpy
,strncat
andstrncmp
, which operate on the mostn
characters of their argument strings. For example,strncpy(s, t, n)
copies at mostn
characters oft
tos
. Full Description in Appendix B.
Here is my implementation of strncmp
:
int custom_strncmp(const char *s, const char *t, size_t n) {
while(n--) {
if(*s != *t) {
return *s - *t;
}
else {
++s;
++t;
}
}
return 0;
}
The while
loop will run until n
reaches the value 0
, or until the characters that s
and t
point to are not equal. At each iteration I check if the *s
and *t
are equal; if they are, I increment s
and t
. If they are not equal, I return their difference.
After the loop stops, the value 0
is returned.
Here is my implementation of strncat
:
char *custom_strncat(char *s, const char *t, size_t n, size_t bfsize) {
size_t slen = strlen(s);
char *pend = s + slen;
if(slen + n >= bfsize)
return NULL;
while(n--)
*pend++ = *t++;
return s;
}
This version of strncat
is a secure one. The first if-statement
checks if there is enough space in the s
buffer to store the contents of t
. The while
loop will run until n
reaches the value 0
. At each iteration the value that t
points to is copied in to *s
.
After the loop stops, is returned a pointer to the result.
Here is my implementation of strncpy
:
char *custom_strncpy(char *s, const char *ct, size_t n) {
char *saver = s;
while(n--)
*saver++ = *ct++;
*saver = '\0';
return s;
}
The while
loop will run until n
reaches the value 0
, at each iteration the current character that ct
points to is copied in *saver
. After the loop stops, the '\0'
is copied in *saver
and a pointer to the result is returned.
The exercise can be found at page 121 in K&R second edition.