Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'
like image 982
dems98 Avatar asked Jan 14 '17 16:01

dems98


1 Answers

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.

like image 167
Sourav Ghosh Avatar answered Oct 08 '22 03:10

Sourav Ghosh