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?

Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

The size parameter specifies the maximum size of the destination buffer.  It is used to prevent buffer overruns.  In your case, the size of the destination buffer is strLen, not sizeof(strTemp) [which you have correctly deduced is sizeof(pointer)].

However, since you are explicitly allocating the destination buffer to be the same size as the source string, the additional security is somewhat unnecessary.


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
JohnSantaFeAuthor Commented:

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".

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.