cpointersscopedereferenceautomatic-storage

Pointer don't lets auto variable to get deleted after the function call


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;
}

Solution

  • 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.