Hi,
Can anyone post the source code for strncpy from linux.
thanks,
Printable View
Hi,
Can anyone post the source code for strncpy from linux.
thanks,
Hi Salem,Quote:
Originally Posted by Salem
I would like to know how it was implemented.
my doubt whether the function is taking care of src buffer null character before the specified no of chars.
for example consider this code
thanks,Code:main()
{
char src[10], dest[10];
strcpy(src, "abcdefgh");
src[5] = '\0';
strncpy(dest, src, 8);
printf(dest);
}
>I would like to know how it was implemented.
Implementations vary. The best resource is a good reference that either quotes or accurately paraphrases the standard.
>my doubt whether the function is taking care of src buffer null character before the specified no of chars.
It sounds like you've discovered the flaw in strncpy. Or rather, the flaw that everyone thinks is a flaw before they discover that strncpy wasn't designed to do what they want to do, but something slightly different, which it does perfectly. :)
It doesn't really matter what strncpy does here, because your abuse of printf is still going to stop at the null character when it displays the string. By definition, a string ends at the null character. You cannot have strings with embedded null characters. The string ends at the first one. Anything after it is considered to be a new string.Quote:
Originally Posted by abc123
Quzah.
But, Anyway thanks for your reponce.Quote:
Originally Posted by quzah
It doesn't matter about the specific implementation. All you have to do is read its description.Quoted from C: A Reference Manual Fifth Edition, page 350.Quote:
The function strncpy copies exactly n characters to dest. It first copies up to n characters from src. If there are fewer than n characters in src before the terminating null character, then null characters are written into dest as padding until exactly n characters have been written[/b]. if there are n or more characters in src, then only n characters are copied, and so only a truncated copy of src is transferred to dest. It follows that the copy in dest is terminated with a null by strncpy only if the length of src (not counting the terminating null) is less than n. If the value of n is zero or negative, then calling strncpy has no effect. The value of dest is always returned.
Now, since we are dealing with strings, and since by definition, the only way you can tell when a string ends is by finding the first (and thusly only) null character, you have your answer quite clearly. The src string ends at the null character you have placed at src[5]. Anything beyond src[5] is considered a seperate string. Therefore, you can deduce that your destination buffer will contain:
abcd(null)(null)(null)(null)
There really isn't any room for doubt here. It's quite clear as to the behavior of the function if you pay attention to the definition of what a string is.
Quzah.