-2
#include<stdio.h>

int * display();

main()
{
    printf("\nHello\n");

    int * a = display();
    printf("%d", *a);
}

int * display()
{
    printf("\n Hi \n");

    int b = 10;
    return &b;
}

Can anyone tell me how does memory allocation work in c?

I'm sure we can access the value of b(in this program), then why can't we access the address of it? I get an error (Segmentation fault).

What is the concept behind it?

I'm a beginner.

LPs
  • 16,045
  • 8
  • 30
  • 61
ChDlGy
  • 67
  • 2
  • 8
  • The program has undefined behavior because the function returns pointer to a local variable that will not alive after exiting the functions. – Vlad from Moscow Feb 17 '17 at 14:25
  • Read this: [Pointer to local variable](http://stackoverflow.com/questions/4570366/pointer-to-local-variable). – Lundin Feb 17 '17 at 15:04
  • AFAIK this is the most viewed OP on SO regarding this issue. It's tagged `c++` but the concepts are the same,, and it has a somewhat practical and fun analogy from Eric Lippert: http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope/6445794#6445794 – yano Feb 17 '17 at 15:17

1 Answers1

2

You shouldn't return pointer to an automatic local variable. It will no longer exist once function return and therefore will invoke undefined behavior.

You can allocate memory dynamically and then return pointer:

  int * display()
  {
      printf("\n Hi \n");

      int *b = malloc(sizeof(int));
      *b = 10;
      return b;
  }
haccks
  • 104,019
  • 25
  • 176
  • 264