Recently, we had a lecture in college, where our professor told us about different things, to be careful when programming in different languages. The following is an example in C ++:
std::string myFunction() { return "it 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 of ββwhy this will lead to an error is that return "it me!!" implicitly calls the constructor std :: string with char []. This string is returned from the function, and the c_str() function returns a pointer to the data from std::string .
Since the string returned from the function is not mentioned anywhere, it should be freed immediately. It was a theory.
However, running this code is no problem. It would be interesting to know what you think. Thank!
c ++
guitarflow Jan 02 '14 at 12:38 on 2014-01-02 12:38
source share