You're returning a local object that gets cleaned up when the function terminates.
This is undefined behaviour, anything can happen.
int _pTest1(void) {
int a = 10; // a local object on the stack
int *_pA = &a; // a local pointer to a local object on the stack
return _pA; // returning a local pointer to a local object,
// wrong as the object pointed to may be cleaned up or overwritten.
}
Furthermore, in _pTest1
you probably wanted to return *_pA
as at the moment you're returning a pointer even though your function signature indicates you want to return an integer.
Actually you can try a small experiment. See if it makes any difference if you return _pA
as a plain pointer (return _pA;
) or as a dereferenced pointer (return *_pA;
). Don't forget to update the function signature and the types you assign the return of the function to.
You'll find that in the latter case the output will be consistent, whereas in the former by the time you dereference the returned address the value may be long gone.
In your second function you are returning a pointer to an argument that is not local to the function. However a
in the function will still have a local address (as arguments in C are always passed by value and a local copy will be made). So returning it is still not guaranteed to result in a meaningful value.
You can prove this with the following code:
int a = 55;
printf("%p\n", &a); // this will have one address e.g. 0xbff51148
int* _pT = _pTest2(a); // _pT points to an address where a local object was held, not reliable
printf("%p\n", _pT); // this will have another address e.g. 0xbff51130