Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading