Search code examples
c++cstringstdstring

std::string.c_str() has different value than std::string?


I have been working with C++ strings and trying to load char * strings into std::string by using C functions such as strcpy(). Since strcpy() takes char * as a parameter, I have to cast it which goes something like this:

std::string destination;
unsigned char *source;
strcpy((char*)destination.c_str(), (char*)source);

The code works fine and when I run the program in a debugger, the value of *source is stored in destination, but for some odd reason it won't print out with the statement

std::cout << destination;

I noticed that if I use

std::cout << destination.c_str();

The value prints out correctly and all is well. Why does this happen? Is there a better method of copying an unsigned char* or char* into a std::string (stringstreams?) This seems to only happen when I specify the string as foo.c_str() in a copying operation.

Edit: To answer the question "why would you do this?", I am using strcpy() as a plain example. There are other times that it's more complex than assignment. For example, having to copy only X amount of string A into string B using strncpy() or passing a std::string to a function from a C library that takes a char * as a parameter for a buffer.


Solution

  • This is not a good idea at all for two reasons:

    1. destination.c_str() is a const pointer and casting away it's const and writing to it is undefined behavior.
    2. You haven't set the size of the string, meaning that it won't even necessealy have a large enough buffer to hold the string which is likely to cause an access violation.

    std::string has a constructor which allows it to be constructed from a char* so simply write:

    std::string destination = source