2

I write a function f() to return local pointer to main function. I know the memory of f() function will be released after it execute. However the f() function can return the pointer which point the array of a[2]. I think a[2] should be released, but it still exist.

So I want to know can I write a function which can return the local pointer and the local pointer point the local variable in the function? If it can return, why array of a[2] would not be released after the end of f() function?

#include <stdio.h>

int* f()
{
  int a[2] = {1, 2};
  int* p = a;
  printf("%p\n", p);
  return p;
}

int main(void)
{
  int* p = f();
  printf("%p\n", p);
  return 0;
}
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
ray
  • 241
  • 2
  • 13
  • C doesn't have its own Garbage Collector, so the variables still hold the memory when the function exits, but the program doesn't have control over those variable as the function call exited and it cannot be guaranteed that those variables cannot be overwritten by some other definitions or declaration of variables. It might be possible that some other function would get the same stack allocated which was allocated by the previous function. – Gaurav Pathak Sep 28 '17 at 06:03
  • 1
    @GauravPathak Note: Being object-oriented does not imply it has a garbage collector. – Havenard Sep 28 '17 at 06:06
  • You cannot return the local pointer and use it later. – msc Sep 28 '17 at 06:07
  • @Havenard I agree! But I guess most of the object-oriented language has GC, if I am not wrong. – Gaurav Pathak Sep 28 '17 at 06:07
  • 1
    @GauravPathak: C++ claims (rightly) to have object-oriented features but does not have any GC. – Basile Starynkevitch Sep 28 '17 at 06:08
  • @GauravPathak Well, most languages nowadays do, regardless of it supporting objects or not. – Havenard Sep 28 '17 at 06:09
  • @BasileStarynkevitch Exactly, so I edited the comment. ;-) – Gaurav Pathak Sep 28 '17 at 06:09

2 Answers2

9

Since the array you point to will go out of scope and cease to exist, attempting to dereference the returned pointer will lead to undefined behavior.

However, in practice the memory will still exist, and if none of the contents have been overwritten by later function calls, it will still be there unmodified. So if you attempt to dereference the pointer you will still see the data. But you should not do that!

Regarding what you're doing, you're not actually dereferencing the pointer, so you don't have UB. All you're doing is printing the value of the pointer itself.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
2

Yes, you can (unfortunately) return the pointer. No, it’s not a good idea. The pointer will point to memory that was marked as no longer used, meaning that if you try to dereference it, you’ll most probably get a segfault. That is, you’ll get a segfault if you’re lucky – if not, you’ll get a random value or some other undefined behaviour.

zoul
  • 102,279
  • 44
  • 260
  • 354