C/return value iv c
Expert: Zlatko - 6/19/2011
QuestionHi Zlatko
arguments and return value stored on stack frame of every function. right..? as shown in the following functions.
int max(int a,int b)
{
return a>b?a:b;
}
char* display()
{
char name[] = "james";
return name;
}
In both cases returning local variables. but why i am able to get int values but not string(retuning local variables is not possible)
can you please explain me what does this mean by returning local variables and how to overcome the problem.
Thanks
Bhupal.
AnswerHello Bhupal
Variables like int and char and float are copied onto the stack when they are returned and then copied into their destination. The same is true for returning pointers, but in the case of the display function, the pointer is pointing to memory declared on the stack and that memory is valid only for the lifetime of the display function. When the display function returns, the memory is reused for other things.
One solution is to return allocated memory. For example
return strdup(name);
The strdup makes a copy of the string "james" on the heap memory. That memory stays valid until it is freed with the free function. The receiver of the pointer would be responsible for freeing the memory when it is no longer needed.
Another solution is to declare the name array static. Doing so will keep it alive even after the function returns.
For example
static char name[] = "james"
I hope that helps you out.
Best regards
Zlatko