News for hackers. Stuff that matters.
Re:Printable True Bugs Wait Posters by ledbettj on Friday January 31, 2014 @09:13AM (#7156670)
Keeping in mind that strncpy has it's own problems, like not null terminating the buffer if it would overflow.
Re:Printable True Bugs Wait Posters by Nursie on Friday January 31, 2014 @09:24AM (#7156723)
I guess the whole point is don't rely on null terminated strings in your code.
Re:Printable True Bugs Wait Posters by lawl on Friday January 31, 2014 @09:29AM (#7156754)
This is why you should use strlcpy()!
Re:Printable True Bugs Wait Posters by santosha on Friday January 31, 2014 @09:32AM (#7156776)
The point of the n is that you specify the maximum length that it's allowed to copy. It's slightly harder to mess that up than with regular strcpy.
Re:Printable True Bugs Wait Posters by tobiasu on Friday January 31, 2014 @10:49AM (#7157227)
The n in strncpy describes to what size the destination buffer (not string) should be padded with '\0'.

This is useful for copying a string into a fixed size buffer that is sent over the network, to give an example. It's not what the programmer generally means when using strncpy.

Many programmers are surprised when they learn that strncpy() really writes 1M-strlen("abc") zeros in the 1M char array every time it's called...

Re:Printable True Bugs Wait Posters by dllthomas on Friday January 31, 2014 @04:09PM (#7159198)
"The n in strncpy describes to what size the destination buffer (not string) should be padded with '\0'."

This is false.

From the man page: "The strncpy() function is similar, except that at most n bytes of src are copied. Warning: If there is no null byte among the first n bytes of src, the string placed in dest will not be null-terminated."

And the following code prints foo:ar on my system.

    char buffer[10];
    strcpy(buffer, "foobar");
    strcpy(buffer, "foo");
    printf("%s:%s\n", buffer, buffer+4);
Edited to add: huh, scratch that. Obvious error in above test :-P. Testing it with strncat like I had meant to, it seems it is in fact padded, not just (possibly) terminated. Interesting, and very worth knowing if you are trying to move a probably small string to a large buffer under time pressure.
Re:Printable True Bugs Wait Posters by tobiasu on Friday January 31, 2014 @05:45PM (#7159687)
What is false? I'm not talking about the source string not being terminated when it's too long. That's obvious and there are plenty posts about it in this thread.

Not sure what you want to say with the example code. Maybe swap it for strncpy and strlcpy and see whether that matches your expectations?

Re:Printable True Bugs Wait Posters by dllthomas on Friday January 31, 2014 @06:02PM (#7159754)
Yeah, my bad, had meant to use strncpy. My contention had been that it only zeroes the first following character (if that). On closer reading of the man page, it is in fact clear.