Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write C string functions: strncpy , strncat , and strncmp

Tags:

c

function

string

I'm solving this K&R exercise:

Write versions of the library functions strncpy , strncat , and strncmp , which operate on at most the first n characters of their argument strings. For example, strncpy(s,t,n) copies at most n characters of t to s . Full descriptions are in Appendix B.

So i was wandering if there's a site that contains source code for these string functions so i could check to see if i did something wrong.

These are the versions i wrote: i would appreciate if you would tell me if i have some bugs in the functions or something i should add/correct/improve!

int strncmp(char *s, char *t, int n)
{

     if(strlen(s) == strlen(t)) {

         while(*s == *t && *s && n) 
            n--, s++, t++;

         if(!n) 
             return 0; /* same length and same characters */
         else 
             return 1; /* same length, doesnt has the same characters */         
     }
     else
        return strlen(s) - strlen(t);
}

char *strncpy(char *s, char *t, int n)
{
     while(n-- && *s) {
        *s = *t;
        s++, t++;
     }

     if(strlen(t) < n)
        *s = '\0';

     return s;
}

char *strncat2(char *s, char *t, int n)
{
     while(*s)
       s++;

     while(n-- && *t) 
       *s = *t, s++, t++;

     *s = '\0';
     return s;
}
like image 880
Tool Avatar asked Dec 11 '25 04:12

Tool


1 Answers

A quick look seems to reveal at least a couple of problems:

  • In strncmp: The strlen() call on the input is not valid. They do not have to be null terminated. Also, the return value should be <0, =0, >0 depending on the equality.
  • strncpy: I believe the library version pads the string with \0 to the end.
like image 171
Mark Wilkins Avatar answered Dec 12 '25 21:12

Mark Wilkins