Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1611
  • Last Modified:

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?

1 Solution
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.

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


Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now