cscopereturn-valuereturn-typestorage-duration

why does returning the local variable address throws an error but returning the local variable value don't?


I can not understand, what is the difference between following function bodies

int func(void){
    int A = 20;
    return A;
}

and

int* func(void){
    int A = 20;
    return &A;
}

why returning the values does not throw the error of the segmentation fault but returning the address do?


Solution

  • A local variable with automatic storage duration is not alive after exiting the scope of the function where it is defined. So the returned pointer will be invalid and de-referencing such a pointer invokes undefined behavior.

    If you will change the second function the following way

    int* func(void){
        static int A = 20;
        return &A;
    }
    

    then returning a pointer to the variable A will be correct because the variable having static storage duration will be alive after exiting the function.

    A returned value can be assigned to a variable or discarded. So there is nothing wrong.