7

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?

Community
  • 1
  • 1
Alex
  • 133
  • 2
  • 3
  • 5

3 Answers3

17

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.

Steve Townsend
  • 51,210
  • 8
  • 87
  • 134
  • 2
    +1 for recommending `std::string` which is *always* the correct answer to a question like this in C++. – Jonathan Grynspan Apr 26 '11 at 16:54
  • I think strncat is a perfectly reasonable way to do this, especially since he's using C strings in this example anyway. – Max E. Apr 26 '11 at 16:58
  • 1
    @Max, yes that would make a good alternative response. I just prefer to avoid CRT if in C++ code, for reasons like the above question. – Steve Townsend Apr 26 '11 at 16:59
2

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.

Doug T.
  • 59,839
  • 22
  • 131
  • 193
  • As for how to fix it, use strncat instead and pass in a count that ensures that the "sentence" string won't overflow. – fredw Apr 26 '11 at 16:54
0

You can use strcat_s to fix the potential buffer overloads.

Daniel A. White
  • 174,715
  • 42
  • 343
  • 413
  • 3
    `strncat` is more standard. `strcat_s` is a proposed standard, but it's nowhere near universally supported. – LnxPrgr3 Apr 26 '11 at 16:55