Bluebaby
Bluebaby

Reputation: 431

Difference between 'strcpy' and 'strcpy_s'?

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?

Upvotes: 41

Views: 86770

Answers (3)

Louis Go
Louis Go

Reputation: 2588

When you thought "hey let's just use strcpy_s which is much safer!". Don't do that before you read all the docs! Because all *_s APIs will call constraint handler if string wouldn't be fully filled.

My two cents: There is NO best API without use cases.

Here's the case for "string copy", concatenation and replacement aren't covered.

  1. Avoid strcpy at any cost. It gets buffer overflow if source string is larger than destination size and it's easy to be overlooked.
  2. Should we use strcpy_s? Yes if you want that every copy is not truncated. It will call installed constraint handler if:
    • src/dest is null
    • truncation would happen (including nul-terminator not copied)
    • overlap between src/dest
  3. What if truncated string in dest is allowed?
    • strncpy is clunky because you need to set nul-terminator in the end if string is larger than count. buf[buf-1]='\0' is annoying..
    • snprintf is handy because even bufsz cannot contain the full string, it fills bufsz-1 and set \0 for you
    • Why not snprintf_s? Because all *_s APIs will call constraint handler if string isn't fully filled

All the referenced keyword are coming from cppreference:

  1. strcpy/strncpy_s
  2. strncpy/strncpy_s
  3. snprintf

Upvotes: 0

Deadlock
Deadlock

Reputation: 4519

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.

Upvotes: 51

Navin
Navin

Reputation: 4115

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.

Upvotes: 2

Related Questions