34

When i tries to use strcpy to copy a string it gave me a compile error.

error C4996 '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.

What is the difference between strcpy and strcpy_s?

U. Windl
  • 3,480
  • 26
  • 54
Bluebaby
  • 361
  • 1
  • 3
  • 4

2 Answers2

45

strcpy is a unsafe function. When you try to copy a string using strcpy() to a buffer which is not large enough to contain it, it will cause a buffer overflow.

strcpy_s() is a security enhanced version of strcpy(). With strcpy_s you can specify the size of the destination buffer to avoid buffer overflows during copies.

char tuna[5];  // a buffer which holds 5 chars incluing the null character.
char salmon[] = "A string which is longer than 5 chars";

strcpy( tuna, salmon ); // This will corrupt your memory because of the buffer overflow.

strcpy_s( tuna, 5, salmon ); // strcpy_s will not write more than 5 chars.
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
Deadlock
  • 4,211
  • 1
  • 20
  • 25
  • 7
    This can be achieved with strncpy as well. The _s adds checking for NULL pointers. – Aki Suihkonen Aug 21 '15 at 09:15
  • 6
    strncpy is not the same thing- heaps of hits on SO. Less efficient, doesn't null terminate. strlcpy is closer. strcpy_s is probably best; neither are fully portable afaik. – radsdau Jan 21 '16 at 02:04
  • 2
    strcpy_s() returns ERANGE if the destination buffer is too small. Radsdau is correct; strncpy() is unsafe. BSD has strlcpy(), Windows has strcpy_s(). Not sure about Linux. Full documentation: https://msdn.microsoft.com/en-us/library/td1esda9 – Edward Falk Jan 29 '17 at 02:19
  • 3
    Since C11 strcpy_s is standard : https://en.cppreference.com/w/c/string/byte/strncpy. – IceBerg0 Dec 12 '19 at 12:44
  • Presumably in the example, strcpy_s( tuna, 5, salmon ) will return an error? ?? – loneRanger Jun 21 '23 at 18:07
1

I'd like to add that if you ever try to compile other people's code, MS will always complain about unsafe functions in the standard library. Just define _CRT_SECURE_NO_WARNINGS like the error message tells you to and MSVC will work like any other compiler.

Navin
  • 3,681
  • 3
  • 28
  • 52
  • 16
    Or better yet, thank MS for pointing out the bad code, and fix it. – Edward Falk Jan 29 '17 at 02:20
  • 2
    You can avoid unsafe functions like strcpy(). To be honest, when I'm writing code that I intend to be portable, I just implement a few functions myself, call them e.g. StrNCpy(), etc. and bundle them into my source. The effort required to do this is really less than the effort to write Makefiles or configfiles or whatever it takes to make sure you're calling the right functions for whatever OS flavor you're building for. – Edward Falk Jan 30 '17 at 20:06