-1

I started studying pointers and I got in some trouble with the next code:

#include <stdio.h>

int * g()
{
    int a = 10;
    return &a;
}

void main()
{ 
    int *p;
    p=g();
    printf("%d",*p);
}

It returns the error segmentation fault. core dumped

I would really apreciate any help. Have a nice day!

mch
  • 9,424
  • 2
  • 28
  • 42

1 Answers1

3

You are returning the address of a local variable. When you leave the function your code does not know this variable anymore, thus the segmentation fault. You would have to give a pointer to this function as a parameter or dynamically create memory for this variable in the heap.

e.g.

void g(int* p) {
  *p = 10;
}

int main() {
  int a;
  g(&a);
  printf("%d", a);
  return 0;
}

or

int* g() {
  int* p = (int*) malloc(sizeof(int));
  *p = 10;
  return p; 
}

int main() {
  int* p;
  p = g();
  printf("%d", *p);
  free(p)
  return 0;
}
SgtDroelf
  • 331
  • 1
  • 18
  • 1
    Yup. OP, you basically wanted to take the pension of a dead relative, which is a crime (with `a` being the relative, end of function being the death, and `Segmentation fault` being the judge's opinion on the matter.) – Amadan Dec 05 '16 at 07:21
  • you can also write `int * g() { static int a = 10; return &a; }` – Destructor Dec 05 '16 at 10:42