Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between 'strcpy' and 'strcpy_s'?

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?

like image 559
Bluebaby Avatar asked Aug 21 '15 08:08

Bluebaby


People also ask

What is the difference between strcpy and Strlcpy?

In computer programming, the strlcpy function is intended to replace the function strcpy (which copies a string to a destination buffer) with a secure version that cannot overflow the destination buffer.

What is the difference between memcpy and strcpy?

strcpy () is meant for strings only whereas memcpy() is generic function to copy bytes from source to destination location. The strcpy ( ) function is designed to work exclusively with strings.

Where is strcpy_s defined?

The strcpy_s() and strcat_s() functions are defined in ISO/IEC TR 24731 as a close replacement for strcpy() and strcat(). These functions have an additional argument that specifies the maximum size of the destination and also include a return value that indicates whether the operation was successful.

Which is better strcpy or strncpy?

strcpy( ) function copies whole content of one string into another string. Whereas, strncpy( ) function copies portion of contents of one string into another string. If destination string length is less than source string, entire/specified source string value won't be copied into destination string in both cases.


2 Answers

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.
like image 131
Deadlock Avatar answered Oct 17 '22 08:10

Deadlock


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.

like image 28
Navin Avatar answered Oct 17 '22 07:10

Navin