The problem as I see it, you're trying to return
the address of a local variable from a function (scope) and trying to access the returned memory from the caller. In the caller, the memory is invalid and any usage will lead to undefined behavior.
Solution: You need to use dynamic memory allocation for the pointer (malloc()
/ calloc()
) which you want to return
from the function. This will overcome the issue here, as the lifetime of the dynamically allocated memory is untill free()
-d manually or till program termination, whichever is earlier.
Having said that, this approach is not a good one. If all you want to return one of multiple types, go for a struct
containing members for all types and use a flag to mark the type. Fill the corresponding member variable, set the flag and return
the structure variable.
For better, you can actually use an union
as a member of the structure, as you only need one type at a time. For a working code, please refer to the other answer by @pmg.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…