Why is “strcat” considered as “unsafe”? [duplicate]
Possible Duplicate:
Why does MSVC++ consider “std::strcat” to be “unsafe&rdqu开发者_Python百科o;? (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?
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.
Because this is legal
char sentence[ 1] = "";
char *article[ 5 ] = { "the", "a", "one", "some", "any" };
lexeme = rand() % 4; // random lexeme
strcat( sentence, article[ lexeme ] ); // BUFFER OVERRUN
strcat( sentence, " " );
Which will let you modify anything on the stack past the sentence array. You could unknowingly cause bugs by overwriting other stack variables without the language or OS stopping you. Also, there's a huge security problem -- stuff on the stack includes pointers back to the function to return to. A clever attacker could insert a pointer back to their code in your data allowing them to execute anything they want.
I reccomend avoiding C style strings whenever possible. Use std::string whenever possible and the Microsoft reccomended security enhancements to the C std lib when you absolutely must work with C strings.
You can use strcat_s
to fix the potential buffer overloads.
精彩评论