C++ – Be wary of strcat() and strcpy()

strcat() and strcpy() are two functions that work with the c-style strings. While the former concatenates two strings, the latter copies one string into the other. Both these functions have been the reason for multitude of bugs in many applications. Although, they are simple functions to use, most programmers are oblivious to their implementation details which has resulted in quirky and hard-to-debug behaviors in several applications .

strcat() accepts two arguments, ( written as strcat(char* a, char *b) )  where ‘a’ and ‘b’ are pointers to character arrays.  It appends the content of ‘b’ to the end of ‘a’ in-place without allocating any new  unused memory to ‘a’. This can result in a buffer overflow when the size of the content being appended exceeds the memory capacity of ‘a’. Any data that was present in these memory locations prior to the overwrite are lost.  strcat() is an expensive operation as the system needs to traverse to the end of ‘a’ before concatenating contents of ‘b’.  strncat() can be used as a replacement to this function which requires ‘size’ as an argument. It only copies as many characters  as specified by ‘size’.

strcpy() works in a similar manner. This function also accepts two arguments ( written as strcpy(char* a, char *b) ) where ‘a’ and ‘b’ are pointers to character arrays. The content present in ‘b’ is written into the memory location of ‘a’ until the ‘\0’ (null character) is encountered. This kind of copy is an expensive operation as the system needs to check if each character it encounters in ‘b’ is equal to the null character. Like strcat(), this function can also lead to buffer overflow when the length of ‘b’ is larger than the memory allocated to ‘a’. memcpy() can be used to perform copy instead of strcpy() as it accepts ‘size’ as an argument along with the string pointers. It stops as soon as the number of characters copied reaches the specified ‘size’ limit.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at WordPress.com

Up ↑

%d bloggers like this: