It's no surprise you have trouble understanding that code, because it is very poorly written.
The main problem is that the a
array in the m()
function ceases to exist when m
returns, so any pointer to that array is no longer valid1, and attempting to read or write anything through an invalid pointer leads to undefined behavior.
"Undefined behavior" simply means that the code is erroneous, but the compiler isn't required to handle it in any specific way. Your program may crash outright, it may be put into a bad state that doesn't manifest until later, it may corrupt data, or it may appear to run without any issues.
So yes, the result may vary, but that's understating the case by a lot. The right answer is "E) The behavior is undefined".
But there are other problems in the code. m()
returns a pointer to int
, but the program assigns the result to a plain int
, hence the first warning. Whoever wrote that code either doesn't understand types, or assumes that pointer values and int
values are interchangeable (not necessarily a valid assumption).
Either that, or the original code is actually
int k = *m();
And, finally, main()
returns int
, not void
, as in:
int main( void ) // or int main( int argc, char **argv ) if your program takes
// command line arguments.
- Obviously, the memory location that
a
occupied still exists, but after m()
exits, that memory may be overwritten or used by something else.