Hello, everyone
I wrote the following sample program but I got an amazing output. I know if I use strdup function, my problem will be solved but I don't want to use this function because I have to free the memory.
Please, help me how to solve this problem.
is that it is trying to return the address of the C-string in the buffer of the local string str.
When it's constructed, the string object str allocates a buffer on the heap and copies "hello" into it.
The c_str() call then gives you the heap address where "hello" can be found at that moment.
But, as str is a local variable, when you return from func1, its (as in, str's) destructor is fired which frees up the buffer. So you end up returning the address of a C-string which was there when you called c_str() but is now gone.
#include <stdio.h>
#include <string>
using std::string;
constchar* func1()
{
// constructed the first time func1 and still here when we come back
staticconst string str = "hello";
return str.c_str();
}
constchar* func2()
{
// ditto
staticconst string str = "hi";
return str.c_str();
}
int main()
{
char s[20];
sprintf( s, "%s\t%s\n", func1(), func2());
printf("%s\n",s);
return 0;
}