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!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…