Difference between 'strcpy' and 'strcpy_s'?
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.
C6387 for memcpy, strcpy and strcpy_s
'strNewBind->cKeyIdentifier' could be '0': this does not adhere to the specification for the function 'memcpy'.
Test for a NULL
return from malloc()
.
size_t n = (strlen(pcKey) + 1) * sizeof(char);
strNewBind -> cKeyIdentifier = malloc(n);
// Add test
if (strNewBind->cKeyIdentifier) {
memcpy(strNewBind -> cKeyIdentifier, pcKey, n);
} else {
Handle_OutOfMemory(); // TBD code.
}
How does strcpy_s work?
This is actually how to get the size of a stack array at run time without decaying it to a pointer:
template<typename T, size_t N>
size_t arrSize(T (&array)[N])
{
return N;
}
You send it as a template reference, and the template mechanism deduces the size. So, you can do something like
int myArray[10];
cout << arrSize(myArray); // will display 10
So my guess is that this is how the "safe" MS strcpy_s
is checking the sizes. Otherwise, if you pass just a pointer, there is NO STANDARD-COMPLIANT way of getting the size.
converting strcpy_s to strcpy CPP
strcpy(this->name, d.getName());
That was easy
Related Topics
How to Implement Timeout for Function in C++
_Iterator_Debug_Level Value '0' Doesn't Match Value '2'
When Extending a Padded Struct, Why Can't Extra Fields Be Placed in the Tail Padding
Enable a Single Warning in Visual Studio
Why Do Objects Returned from Bind Ignore Extra Arguments
Convert String with Explicit Escape Sequence into Relative Character
Most Terse and Reusable Way of Wrapping Template or Overloaded Functions in Function Objects
Hooking Directx Endscene from an Injected Dll
How to Build Google's Protobuf in Windows Using Mingw
How to Do Input Validation in C++ with Cin
Is There an Automatic Noexcept Specifier
Arithmetic Right Shift Gives Bogus Result
How to Compile for Windows Xp with Visual Studio 2012
Why Doesn't C++ Move Construct Rvalue References by Default
Why Doesn't Reinterpret_Cast Force Copy_N for Casts Between Same-Sized Types