Im trying to pass a character array
value to a character pointer
. then this value gets returned to a method that is calling it, but after it gets returned, the value becomes garbage. can anyone help me?
#include <stdio.h>
const char * getname(){
char nam[10];
char * name;
gets(nam);
name = nam;
return name;
}
main(){
printf("%s",getname());
getch();
}
everything is fine, until the string gets returned
Your problem is that
return name
is returning the address of a stack variable, one that's gone out of scope after the function returns.There are a couple of ways to fix this (at least).
The first is to have the address allocated outside of the function and then passed in:
The second is to use allocation functions that don't go out of scope on function exit (the pointers may but, as long as you pass them back, you can still get to the allocated memory):
The
nam
variable has function scope. This means that once the function ends, the memory for that variable is freed. So the pointer pointing to that memory that you return will not be valid any more.You could pass in the pointer: (a bit pointless in this case, as you can see)
You could
malloc
(bad, because then you need tofree
it again at some point):Scope of
nam
is local to function getname(), you are returningnam
address throughname
pointerallocate memory for
nam;
dynamically. like:additionally there may be bufferoverun don't use
gets()
, do like:You also not need to use
name
an extra variable simplereturn nam
is good.Declaring
nam
static would do also:Beware: This code isn't thread-safe, as
nam
now is treated as if it were declared globally.