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.
- Code 1 is also returning address of a local variable, so why no warning? 
- 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)? 
- 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;
}
 
    