Returning a pointer isn’t a problem as long as it points to memory that is still in scope, such as dynamically allocated memory, global data, or local variables that still exist further up the call stack.
The problem with the above code is that you’re dereferencing a pointer without assigning anything to it. This: *ret_val = 1234;
assigns the value 1234
to the address that ret_val
points to, but ret_val
wasn’t assigned anything.
If on the other hand you did this:
int* foo(void)
{
int * ret_val;
ret_val = malloc(sizeof(int));
*ret_val = 1234;
return ret_val;
}
That is fine since you’re returning a pointer to dynamically allocated memory.
2
solved Pointer returns and scope