Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
507 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...