Abstract: When you put the correct arguments of strncpy, there is a case that your char[] buffer may not contain a valid C string anymore. The strncpy function has this unexpected behavior because of the standard specification. It is also mentioned in the ``Writing Solid Code'' as a defect of function design. Actually, Stroustrup's C++ Programming Language book mentioned it, and the book suggests to not to use it. (at page 600 of the third edition.) But it is mentioned in one line comment of a sample code. I think people usually can not realize that except someone have been bitten by this bug like me.
const int NBUF = 4; char *pS0 = "This string has more than 4 characters."; char s1[NBUF]; strcpy(s1, pS0); // Buffer overrun. A cracker love this code!
const int NBUF = 4; char *pS0 = "This string has more than 4 characters."; char s1[NBUF]; strncpy(s1, pS0, NBUF); // no buffer overrun.But, in this case, the string s1 is not terminated by '\0'. This is written in manual, but this is not not intuitive. Next time you use this, you may have a problem. This 'may' is really nasty. If you get always the same problem, it is much easy to detect that. However, sometimes this bug hide. Next code is correct. But, If the pS0's length is less than NBUF, the last line is not necessary. Therefore, some people may complain this code. However, knowing the length of string is prone to costly, and also there is buffer overrun (read) problem.
const int NBUF = 4; char *pS0 = "This string has more than 4 characters."; char s1[NBUF]; strncpy(s1, pS0, (NBUF - 1)); // no buffer overrun. s1[NBUF - 1] = '\0'; // This is at least correct.
char s[1];
not gcc extension char
s[0]
.)