14 ms·
I'm curious what Linux has against the strl* functions. He says that they can be implemented wrong too, but it seems like they are harder to screw up than the
by jandrese 11y ago
I'm curious what Linux has against the strl* functions. He says that they can be implemented wrong too, but it seems like they are harder to screw up than the strn* versions that required you to manually terminate the string when it hits maximum length.
- icebraining 11y agohttps://lkml.org/lkml/2015/4/28/570 https://lkml.org/lkml/2015/4/28/570
- cremno 11y ago>the strn* versions that required you to manually terminate the string when it hits maximum length This is from the description of the not-easy-to-use strncat(): >A terminating null character is always appended to the result. So your statement is only true for strncpy(). Unlike many other C functions it doesn't deal with C strings (null-terminated character arrays), but rather with fixed length and possibly null padded character arrays. People are just misusing it for some false sense of security. It may seem strange but snprintf() is the only secure string copy function defined by ISO C99.
- mzs 11y ago$ ./a.out kjv.txt Hmm... Why is this taking so long? ^\ $ db core ... a.c:28:strlcpy(dst, src, 8); ... > d src 0040000: 496e 2074 6865 2062 6567 696e 6e69 6e67 In the beginning 0040010: 2047 6f64 2063 7265 6174 6564 2074 6865 God created the 0040020: 2068 6561 7665 6e73 2061 6e64 2074 6865 heavens and the 0040030: 2065 6172 7468 2e20 4e6f 7720 7468 6520 earth. Now the ... Oh, that's why.
- jandrese 11y agoThat doesn't explain anything. The manpage explains the problem though: RETURN VALUES The strlcpy() and strlcat() functions return the total length of the string they tried to create. For strlcpy() that means the length of src. For strlcat() that means the initial length of dst plus the length of src. While this may seem somewhat confusing, it was done to make trunca- tion detection simple. So strlcpy/strlcat parse all of src regardless of what you pass on that third parameter. And they'll happily run off the end of the buffer if your string isn't null terminated. I see what Linus was so mad about now. All because they want to return the length of the original string instead of the length of the copied string. The underlying problem is that C is too limited in return types from functions. There should really be a fourth (optional) flag to strncpy that is set if the string was truncated to fit in the new buffer, and the function would return the number of characters copied, not the number of characters in the source string.
- mzs 11y agoTrue, but another problem for kernel is when something takes too long, which is what I was highlighting in a light hearted manner. The different return is more like what MS does with the _s routines, though it uses a special length return and flag option.