0

When I use a pointer instead of referencing operator in a function pointer do not allow auto variable to get deleted after function call.

I got Segmentation fault (core dumped) from this code because int i=7; is an auto variable and after the function call it gets deleted.

#include<stdio.h>

int *func() {
  int i = 7;
  return &i;
}

int main(void) {
  int *a;
  a = func();
  printf("%d", *(a));

  return 1;
}

But when I use an extra pointer instead of referencing operator I do not get any error and get 7 as output. Why this pointer don't allow to delete variable i?

#include<stdio.h>

int *func() {
  int i = 7;
  int *ip = &i;
  return ip;
}

int main(void) {
  int *a;
  a = func();
  printf("%d", *(a));

  return 1;
}
  • "do not allow auto variable to get deleted after function call." The variable is deleted. You are not allowed to look at that memory location. – Gerhardh Mar 08 '23 at 08:35
  • "... auto variable to get deleted after function call." Well, on most systems variables with automatic storage duration isn't really deleted when a function returns. Your variable `i` is (on most systems) still present in stack memory with the value 7. So as long as that part of the stack hasn't been used by other code (typically a function call), you'll read the value 7 **if** you have the correct pointer value to that memory. In your first code example it is most likely the compiler that decides to return NULL instead of the real `&i`. It is allowed to do that .... – Support Ukraine Mar 08 '23 at 08:54
  • .... because it can see that it is a pointer to a local variable. In the second example it seems the compiler "can't see" that `ip` is also pointing to a local variable so the actual value is returned and you can access the value of `i` using that pointer. That's what my `gcc` compiler do. Instead of `printf("%d",*(a));` try `printf("%p", (void*)a);` In both cases your program has undefined behavior. – Support Ukraine Mar 08 '23 at 08:57
  • So because of it this is something should not to do. It has an undefined behaviour and its result can changed between systems. – A_normal_guy Mar 08 '23 at 09:02
  • @Gerhardh, it's even worse. All copies of this pointer become indeterminate. Any use of their values results in UB. – tstanisl Mar 08 '23 at 11:23

1 Answers1

2

The both programs have undefined behavior because after calling the function func there is an attempt to dereference an invalid pointer that does not point to an existent object.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335