Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this work: returning C string literal from std::string function and calling c_str()

Tags:

c++

We recently had a lecture in college where our professor told us about different things to be careful about when programming in different languages. The following is an example in C++:

std::string myFunction() {     return "it's me!!"; }  int main(int argc, const char * argv[]) {     const char* tempString = myFunction().c_str();      char myNewString[100] = "Who is it?? - ";     strcat(myNewString, tempString);     printf("The string: %s", myNewString);      return 0; } 

The idea why this would fail is that return "it's me!!" implicitly calls the std::string constructor with a char[]. This string gets returned from the function and the function c_str() returns a pointer to the data from the std::string.

As the string returned from the function is not referenced anywhere, it should be deallocated immediately. That was the theory.

However, letting this code run works without problems. Would be curious to hear what you think. Thanks!

like image 718
guitarflow Avatar asked Jan 02 '14 12:01

guitarflow


People also ask

What is the purpose of the c_str () member function of std::string?

std::string::c_strReturns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of the string object.

How does c_str () work?

The c_str() method converts a string to an array of characters with a null character at the end. The function takes in no parameters and returns a pointer to this character array (also called a c-string).

What does std::string () do?

std::string class in C++ C++ has in its definition a way to represent a sequence of characters as an object of the class. This class is called std:: string. String class stores the characters as a sequence of bytes with the functionality of allowing access to the single-byte character.

What does string c_str return?

The c_str method of std::string returns a raw pointer to the memory buffer owned by the std::string .


1 Answers

Your analysis is correct. What you have is undefined behaviour. This means pretty much anything can happen. It seems in your case the memory used for the string, although de-allocated, still holds the original contents when you access it. This often happens because the OS does not clear out de-allocated memory. It just marks it as available for future use. This is not something the C++ language has to deal with: it is really an OS implementation detail. As far as C++ is concerned, the catch-all "undefined behaviour" applies.

like image 114
juanchopanza Avatar answered Sep 30 '22 00:09

juanchopanza