Log in

No account? Create an account
I've just spent an hour debugging part of our operating system… - brad's life — LiveJournal [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: 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)