Difference between 'strcpy' and 'strcpy_s'?
Asked Answered
C

2

39

When I tried 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?

Cocoa answered 21/8, 2015 at 8:51 Comment(2)
"See online help for details" i.e. look up references for both functions.Ellamaeellan
Put your cursor in the word "strcpy". Press F1.Rascal
F
49

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.
Forbidden answered 21/8, 2015 at 8:53 Comment(5)
This can be achieved with strncpy as well. The _s adds checking for NULL pointers.Corse
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.Marna
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: msdn.microsoft.com/en-us/library/td1esda9Sixteenth
Since C11 strcpy_s is standard : en.cppreference.com/w/c/string/byte/strncpy.Calamanco
Presumably in the example, strcpy_s( tuna, 5, salmon ) will return an error? ??Confute
W
2

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.

Wagers answered 21/8, 2015 at 9:10 Comment(2)
Or better yet, thank MS for pointing out the bad code, and fix it.Sixteenth
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.Sixteenth

© 2022 - 2024 — McMap. All rights reserved.