Raghu Srikanth Reddy
Raghu Srikanth Reddy

Reputation: 2711

Implementation of strncpy

I have tried implementing the string n copy function. I have succeeded in it but I tried to optimize my code which isn't working.

char *mystrncpy(char *dst, const char *src, size_t n)
{
   int i;
   char *temp;
   temp = dst;  
   for (i = 0; i < n; i++)
      *dst++ = *src++;
   return temp;
}

The above code is working fine.

But the below one has some problems. It is just returning the src string for whatever n value I pass.

char *my_strncpy(char *dst, const char*src, size_t n)
{
   char *temp = dst;
   while ((*dst++ = *src++) && (--n));
   return temp;
}

Upvotes: 1

Views: 16199

Answers (3)

Alisher Aliev
Alisher Aliev

Reputation: 13

You can use this code, the simpler the better !

void Strncpy( char* _dst, const char* _src, size_t _n )
{
   size_t i = 0;
   while(i++ != _n && (*_dst++ = *_src++));
}

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

These two fragments of code are not equivalent:

  • the first one goes through and copies all n characters regardless of the content of the string;
  • the second one stops right after copying the null terminator, or upon copying n characters, whichever comes first.

Neither first nor the second implementation is equivalent to strncpy from the standard library, which copies up to the terminator, and then continues on to fill the remaining space with zeros. To make your function standard-compliant, add this line before the return statement:

for (; n-- ; *dst++ = '\0');

Another thing to note is that the intent behind strncpy is often misunderstood: it is there to handle fixed-length strings, not variable-length strings with a fixed limit. That is why you need to null-terminate the results that you get from strncpy: if the src string is longer than n characters, the resultant string would not be null-terminated.

Upvotes: 6

Olaf Dietsche
Olaf Dietsche

Reputation: 74028

The second version doesn't work, because it might go one beyond n. Pull the test for n == 0 in front

while (n-- && (*dst++ = *src++))
    ;

and don't put the ; at the end of the line. It is easily missed there.

You can see a sample implementation at man strncpy

Upvotes: 3

Related Questions