?

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....

DESCRIPTION
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?
LinkReply

Comments:
From: evan
2000-05-10 11:12 pm (UTC)

strncpy

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)