strncat() 总是空终止吗?

Does strncat() always null terminate?

考虑这段代码:

limit = sizeof(str1)-strlen(str1)-1;
strncat(str1,str2,limit);

如果 str2 长度大于 limitstrncat Nul 是否终止 str1 或我必须添加此代码,例如 [=16] =]?

str1[sizeof(str1)-1] = '[=11=]'

总是null-terminate。

引用 C11,章节 §7.24.3.2,(强调我的

The strncat function appends not more than n characters (a null character and characters that follow it are not appended) from the array pointed to by s2 to the end of the string pointed to by s1. The initial character of s2 overwrites the null character at the end of s1. A terminating null character is always appended to the result.

以及脚注

Thus, the maximum number of characters that can end up in the array pointed to by s1 is strlen(s1)+n+1.

低于 C11 的 C++ 版本不会在大小写中附加空字符,例如当您的源字符串内部没有足够的 space 用于目标字符串时。

char str[5];
str="Ami"

char str2[10];
str2="NotGoing"

str 有 2 个空闲 space 但需要 7 个连接 str2 和 1 个空字符。 strncat(str,str2,);// 没有空终止的情况。

现在如果 str 没有 space 将整个目的地 (str2) 连同 str 预先写入的数据一起写入其中,因此在这种情况下,它不会在末尾添加空字符

char str[10];
str="Ami"

char str2[3];

str2="Hello"

str 得到足够的 space 用于其中的 str2。所以会在末尾添加一个空字符。

strncat(str,str2,);// case with null termination.

正式的我自己检查

分配给 str 的长度 >= strlen(str)+ strlen(str2)+1 ;

如果满足此条件,您将得到一个空终止结果,否则不会。**