Generally, when you have a "factory" function that creates and returns a pointer to an object, the object should be allocated on the heap with malloc()
, like so:
int *factory(){
int *p;
p = malloc(sizeof(whatever));
return p;
}
In C, function returns are by value. In this case, while p
is a local, stack-allocated variable, it is a pointer and its value (which is what is passed back to the caller) will be the address of the heap-allocated object returned by malloc()
so it is a meaningful value outside the scope of the function.
In your function create_point()
, you're returning a pointer, but because p
is a local (automatic) variable, it is allocated on the stack and so the pointer to it that you're returning will refer to an address that had been in create_point()
's stack frame. Depending on how a given compiler orders automatic variables on the stack (and what order you access them in) as well as other information it needs to place there per the ABI, it's possible that you might have gotten lucky and received the results you expected if you only called create_point()
once, and you would have never detected this error. But the second call's stack frame is likely in the same position as or overlaps with the position of the first call's stack frame on the process's stack, meaning that some or all of the contents left over from the first call (since a function call's stack frame generally isn't cleared once the function returns, the old values will still be there until those memory locations are overwritten) would get clobbered by both the second call to create_point()
as well as the subsequent calls to printf().