Reputation: 18171
Simple program that gets char pointer and puts it to the output.
char * get()
{
char ss [256];
sprintf (ss,"%d",1);
return ss;
}
int _tmain(int argc, _TCHAR* argv[])
{
char *f = get();
cout<<f;
char d[50] ;
cin>> d;
}
I got only garbage on output. Why?
Upvotes: 1
Views: 371
Reputation: 10605
When the get() function returns, the local variable goes out of scope. I.e., it's value becomes undefined.
To solve, you can use...
static char ss[255];
// or
char *ss = (char *)calloc(1,255);
// or with C++
char *ss = new char[255];
or so on...
You decide the trade-off. With a static variable, every call to get() could change the contents of the buffer. But with an approach involving allocation, your caller needs to free the memory and know whether to use free() or delete. Some approach the problem by supplying the buffer to the function when called, like...
void get(char *buf, int limit);
// or
void get(char *buf, int& limitActual);
Then main thing is that when dealing with strings, in C/C++ (even std::string) you are dealing with memory that has to be managed somehow. With string, be very careful with automatic variables.
Upvotes: 2
Reputation: 34625
Function is returning the address of a local variable. The code has undefined behaviour and gives unpredicted results.
ss
resides on stack and the function get()
returns a pointer to it.
char * get()
{
} // Life time of ss ends here
Use std::string instead.
Upvotes: 7
Reputation: 671
Your array ss[] only exists within the scope of get().
So the pointer to it that you return from get() is invalid as soon as you leave the function.
Upvotes: 2