Why is “strcat” considered as “unsafe”?

Alex picture Alex · Apr 26, 2011 · Viewed 18.1k times · Source

Possible Duplicate:
Why does MSVC++ consider “std::strcat” to be “unsafe”? (C++)

Here is my code:

char sentence[ 100 ] = "";
char *article[ 5 ] = { "the", "a", "one", "some", "any" };

lexeme = rand() % 4; // random lexeme
strcat( sentence, article[ lexeme ] );
strcat( sentence, " " );

While debugging in MSVC++ it gives me these warning messages:

Warning 1   warning C4996: 'strcat': This function or variable may be unsafe. Consider using strcat_s instead.
Warning 2   warning C4996: 'strcat': This function or variable may be unsafe. Consider using strcat_s instead. 

How can I fix it?

Answer

Steve Townsend picture Steve Townsend · Apr 26, 2011

This is because there's nothing to stop you from strcat-ing more than 100 bytes into your sentence buffer, with undefined results up to and including heap corruption, stack corruption, program exit, even somebody owning your machine if the data past the 100th byte is appropriately constructed. This is a common class of security vulnerability called a buffer overflow.

To avoid this, use std::string's operator+, this is C++ after all. The CRT need not confine you any longer.