Can an Int * function return an int address?

78 Views Asked by At

So an int* function must retur a pointer to an int, but if a pointer to an int is assigned an int address, could an int* function return an int address? If not, why is it wrong? Thanks

int * function(){

    int a = 4;

    return &a;
}
1

There are 1 best solutions below

4
Vlad from Moscow On

Within the function

int * function(){

int a = 4;

return &a;
}

the variable a is a local variable of the function with automatic storage duration that will not be alive after exiting the function. So the returned pointer will have an invalid value and you may not dereference such a pointer. Otherwise the program will have undefined behavior.

You could declare the variable as having static storage duration like

int * function(){
    static int a = 4;

    return &a;
}

In this case the variable will be alive after exiting the function. So the returned pointer will have a valid value.

Another approach is to allocate an object dynamically and return a pointer to the allocated object as for example

int * function(){
    int *p = malloc( sizeof( *p ) );

    if ( p != NULL ) *p = 4;

    return p;
}