C programming strcat string.h

In C programming the <string.> strcat function appends one string to another.This function simply concatenate two strings.The declaration of the function is given below.

char *strcat(char * restrict s1 ,
 const char * restrict s2);

s1 -The first string.

s2 -This string is append to ‘s1’.

Return type
char* -Returns the value of s1.

Note the null-terminating character of ‘s1’ is over written by the first character of ‘s2’.If the memory of s1 and s2 overlap the behavior is undefined.A simple code example is given below.

Code example

char s1[20] = “New”, s2[] = “Old” , *s3 ;

s3=strcat(s1 , s2);

printf(“s1=%s \n s3=%s” , s1 , s3);



Another code example is given below where the two memory overlap.

Code example

char s1[20] = “C and C++ rocks!” , *s3 ;

s3=strcat(s1+2 , s1+6);


If you compile the program using VS it will throw an exception while Code::Blocks gives a segmentation fault error,all these simply mean the compiler doesn’t favor calling “strcat” when the two memory overlap.

*Side Note

There is no limit on how many characters are appended to the ‘s1’ until a null-terminating character is encountered.It is the programmers responsibility to make sure that there is enough memory available at the destination to accommodate the appended string.So for security reasons you should consider using ‘strncat’ which limit the number of characters appended to the destination memory by specifying the number of characters accordingly.

Related links

->C strncat string.h