JohnSantaFe
asked on
strcpy_s to copy a string
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?
Thanks!
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?
Thanks!
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
I see what you mean. After thinking more about it, this method actually seems more secure than declaring a char that's too large "just in case".