strcpy_s to copy a string
Posted on 2006-04-03
I've got the following code used to copy a string to a c style string which does not work:
myFunct(const string *str)
int strLen = str->length() + 1;
char *strTemp = new char[strLen];
strcpy_s(strTemp, sizeof(strTemp), str->c_str());
//do something with strTemp
delete  strTemp;
The second parameter to strcpy_s, sizeof(strTemp), is too small to hold the incoming str->c_str(). It's only four bytes I'm assuming because it is a pointer.
I tried changing the sizeof call to use the dereferenced pointer as folllows, but that just returns 1 byte;
strcpy_s(strTemp, sizeof(*strTemp), str->c_str());
I could just use strLen as the size of the destination buffer, but it seems that would defeat the security.
What is the correct and secure way to copy a string to a C style string? Any comments on this method of copying?