Log in

No account? Create an account
brad's life [entries|archive|friends|userinfo]
Brad Fitzpatrick

[ website | bradfitz.com ]
[ userinfo | livejournal userinfo ]
[ archive | journal archive ]

[May. 10th, 2000|10:26 pm]
Brad Fitzpatrick
I've just spent an hour debugging part of our operating system project and finally now just traced it down to my misunderstanding of the strncpy() function....

The strcpy() function copies the string pointed to be src (including the terminating `\0' character) to the array pointed to by dest. The strings may not overlap, and the destination string dest must be large enough to receive the copy.

The strncpy() function is similar, except that not more than n bytes of src are copied. Thus, if there is no null byte among the first n bytes of src, the result wil not be null-terminated.

In the case where the length of src is less than that of n, the remainder of dest will be padded with nulls.
Why does it null-pad it? I don't see that as being particularly beneficial. I don't mind it... and now that I understand that n should be the MIN(src, dst) it's all good... but it seems unnecessary. Evan? Scott?

[User Picture]From: hijinx
2000-05-10 10:46 pm (UTC)


If you are expecting something to be there, and it ends up being random, it can be bad.

It may not be useful in this case, but in other cases it is, especially since you can use this to copy things other than just chars, ie. structs, etc.

(Reply) (Thread)
[User Picture]From: d4b
2000-05-11 07:45 am (UTC)

Re: hrmm

Amen! The whole idea here is to safely copy to an area without risk of overwriting into the next portion of memory. The same times that you are concerned about such safety, (and when aren't you? ;-), you don't want to leave garbage in your destination, either.

(Wow! I actually remember something from my earlier days of C! I started learning C in 1984, before the language's standards were fully, uh, standardized. That was a fun time! :-)
(Reply) (Parent) (Thread)
From: evan
2000-05-10 11:12 pm (UTC)


void strncpy(char *dst, char *src, int n) {
int i;
for (i = 0; i < n; i++) {
*dst++ = *src;
if (*src != 0) src++;

Would give the desired behavior. I don't see a good reason to pad with NULs, though.
(Reply) (Thread)