简体   繁体   中英

Does strncat() always null terminate?

Considering this code:

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

If str2 length is greater than limit , does strncat Nul terminates str1 or I have to add this code, like in the case of strncpy ?

str1[sizeof(str1)-1] = '\0'

It always null-terminate.

Quoting C11 , chapter §7.24.3.2, ( emphasis mine )

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.

and, the footnote

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

C++ version lower than C11 doesn't append null character in Case like when your source string has not enough space inside for destination string.

char str[5];
str="Ami"

char str2[10];
str2="NotGoing"

str has 2 free space but needed is 7 to concat str2 and 1 for the null character. strncat(str,str2,);// case with no null termination.

now if str don't have space to write the whole destination (str2) inside it along with str pre-written data so in this case, it will not add a null char at the end

char str[10];
str="Ami"

char str2[3];

str2="Hello"

str got enough space for str2 inside it. so will add a null character at the end.

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

Formal I made to check on my own

length allocated to str >= strlen(str)+ strlen(str2)+1 ;

if this condition satisfies you will have a null terminated result otherwise you not.**

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM