I have a device that can either be a "Router" or a "Switch". I use the below function, passing it an enum that returns me the string. My question is that the memory for whoami is allocated on the stack. When this function devicetype_string finishes, the stack is destroyed. Would this not cause an issue when i use a pointer thats pointing to a memory allocated on the stack?
The current code works. I just want to understand why it works. I would presume that a cleaner and a portable solution would be to malloc memory to hold whoami (so that it goes to the heap) and the calling function should free that memory.
This is the current program:
char *devicetype_string (FwdrType devicetype)
{
char *whoami;
switch (devicetype)
{
case FWDR_TYPE__ROUTER:
whoami = "Router";
break;
case FWDR_TYPE__SWITCH:
whoami = "Switch";
break;
default:
whoami = "Fwder Type UNKNOWN";
}
return whoami;
}
foo()
{
. . .
FwderType abc = FWDR_TYPE__ROUTER;
printf ("%s", devicetype_string(abc));
}