Search code examples
cpointersdynamic-memory-allocationdangling-pointer

Returning the address of a local variable and dynamically created variable


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;
}

Solution

    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: