-1

Code 1:

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

Code 2:

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

OUTPUTS:

Code 2 ----> [Warning] function returns address of local variable [-Wreturn-local-addr] Still gives correct output(10)

Code 1 ----> Works fine. No warnings, no errors.

I have many questions.

  1. Code 1 is also returning address of a local variable, so why no warning?

  2. Code 2 gives warning, which I understand, that I am returning the address of a local variable. When the execution of function g is completed, the stack record is popped off and hence, there is a case of dangling pointers. Still, when I run it, why does it give correct output(10)?

  3. Code 1 works with No warnings, no errors. But is it a good practice?

P.S the main function is same for both scenarios.

int main()
{
    int *v=g();
    printf("%d",*v);
    return 1;
}
sukhbir1996
  • 156
  • 8
  • 1) Not the address but its value 2) Its undefined behavior so it might work might not 3) Its okay if you dont forget to free it – Eraklon Mar 19 '21 at 11:57

1 Answers1

5
  1. Code 1 is not returning address of a local variable but returning an address of a region allocated on the heap, so it is fine.
  2. Undefined behavior is invoked and you got the result by chance.
  3. The function g has two problems:
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
  • So in code 1, that variable's storage is not in stack, but in heap? Thank you so much for clearing this detail up for me. – sukhbir1996 Mar 19 '21 at 12:02
  • Normally, i always check the result of malloc, but this was a test code, so i didn't. And for casting the result of malloc(), this is entirely new information for me! In my university exams, I didn't put the (int *) typecast, and I got my marks deducted! – sukhbir1996 Mar 19 '21 at 12:04
  • 1
    The variable `p` itself is on the stack. An address for heap is stored in the variable `p` and the stored address is returned. – MikeCAT Mar 19 '21 at 12:33
  • Ok. Thank you for making it crystal clear now. – sukhbir1996 Mar 19 '21 at 12:37