-4
int * foo()
{
  int b=8;
  int * temp=&b;
  return temp;
}

I have few questions,

  1. In which part of memory layout does *p present.
  2. I am copying the local variable address to the temp pointer without allocating the memory. But even then it stores the address of the local variable, how it is possible?.
  3. The program works fine for me, when i dereference it (the local variable definitely will not be there) how come i get the value still.

Really not understand anything. Can anyone please explain all my above queries in detail.

Cœur
  • 37,241
  • 25
  • 195
  • 267

2 Answers2

3

Returning the address of the local variable leads to undefined behavior when the returned address is accessed outside the function.

The lifetime of the variable b is just within the function foo() it can't outlive that function so accessing the location within that function is fine but you can't return the address of it and access it outside the function.

Gopi
  • 19,784
  • 4
  • 24
  • 36
3

In which part of memory layout does *p present.

There's no p in your program.

I am copying the local variable address to the temp pointer without allocating the memory. But even then it stores the address of the local variable, how it is possible?.

The local variable has an address. You can return that address.

The program works fine for me, when i dereference it (the local variable definitely will not be there) how come i get the value still.

Code with bugs does strange things you don't expect. Fix the bug and the mystery will go away.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278