Difference Between 'Strcpy' and 'Strcpy_S'

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



Leave a reply



Submit