Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ 'strcpy' gives a Warning (C4996)

Tags:

c++

visual-c++

I am getting this warning but all functions working properly .

what does this really means?

'strcpy': This function or variable may be unsafe. 
Consider using strcpy_s instead. To disable deprecation, 
use _CRT_SECURE_NO_WARNINGS. See online help for details.
like image 906
Sudantha Avatar asked Oct 25 '10 06:10

Sudantha


3 Answers

This function (strcpy) is considered unsafe due to the fact that there is no bounds checking and can lead to buffer overflow. (Actually strcpy is infamous for overflow exploits and all programmers avoid it-or at least should avoid it). The advice is to use a safe function which takes into account the size of the destination buffer to avoid overflow. You could also use strncpy (BUT with caution!). There is no problem with your code, i.e. the functions will run as you say but try giving as input a buffer that is larger than the destination buffer. The function will overflow the destination buffer. Check this also link text

like image 81
Cratylus Avatar answered Oct 05 '22 01:10

Cratylus


While strcpy is a common string function, it has a history of being the source of many bugs and security holes in software (due to the ease of buffer overflows).

Microsoft, in an effort to promote safer coding in C and C++ has provided a suite of replacement functions for the dangerous string methods. Typically they have the original name postpended with _s. Hence the Microsoft secure version of strcpy is strcpy_s as recommended in the warning. Note this a Microsoft specific feature, it's not ubiquitious.

You've got a few options.

  1. DEFINE _CRT_SECURE_NO_WARNINGS if you don't want to care about it, leaving the possibility of the security issues in your software.
  2. Replace your string functions with the secure ones, leaving your software less portable as a consequence
  3. Wrap the secure string functions and use the wrappers everywhere, providing enhanced security on Windows platforms, and falling back to the traditional versions on other platforms. The wrapper functions could be via a MACRO or compiled functions.

I typically do #3.

like image 23
Montdidier Avatar answered Oct 05 '22 02:10

Montdidier


Since you’re programming C++, the correct solution is to ban C-style char* strings from your code where possible, and replace them by std::string (or another appropriate string type).

Do not use functions such as strcpy or strcpy_s or strncpy. Use the copy constructor or assignment operator of the string class. Or if you really need to copy buffers, use std::copy.

like image 10
Konrad Rudolph Avatar answered Oct 05 '22 01:10

Konrad Rudolph