adi_tdkr
adi_tdkr

Reputation: 127

Returning pointer in function

Why don't I get 20 as output in second printf statement?

int main() {
    int *p;
    int * fun();
    p = fun();
    printf("%d\n", p);
    printf("%d", *p);

    return 0;
}

int * fun() {
    int i = 20;
    return (&i);
}

Upvotes: 1

Views: 85

Answers (3)

Vlad from Moscow
Vlad from Moscow

Reputation: 310990

The variable i in the function is its local variable that is in general destroyed after exiting the function. So the returned pointer is invalid and the program has undefined behavior.

You can change the function the following way

int * fun( void )
{
    static int i = 20;
    return &i;
}

In this case the variable i will have static storage duration and will be alive after exiting the function.

Take into account that in C the following declarations

int * fun();

and

int * fun( void );

are not equivalent.

The first declaration means that there is nothing known about the function parameters. You should declare your function like

int * fun( void );

Also main without parameters should be declared in C like

int main( void )

And to output a pointer you should use format specifier %p instead of %d as you do

printf("%p\n",p);
        ^^^

Upvotes: -1

John Bode
John Bode

Reputation: 123468

When fun exits, the local variable i ceases to exist, and any pointer to it is now invalid. Obviously, the memory cell that i used to occupy still exists, but it is now available for something else to use and may be overwritten between the time fun returns and you attempt to print *p.

Either have the function return the value of i:

int fun( void ) { int i; ...; return i; }

or write to a parameter

void fun( int *i ) { ...; *i = 20; ... }

If i had been declared static:

int *fun( void ) { static int i; i = 20; return &i; }

then this would work as you expect, since static objects exist over the lifetime of the program. However, it's not a good solution for this particular problem.

Upvotes: 3

Ishay Peled
Ishay Peled

Reputation: 2868

You can't allocate an integer on stack (inside function scope in your case) and use it outside the scope.

The reason for this is that the memory allocated for your function (= the stack) is considered free after the function ends.

To dig a bit dipper - your process has virtual memory provided by the operating system. This memory is managed by the process and each function you call gets a disposable memory allocated to it by the process (this is the stack). Once the function returns, that memory is recycled by the application for other uses

so in your example:
call int *fun() <- all variables you declare and use, including alloca in this function exist in the function stack
return &1 <- now the function ended and the memory allocated for it is vacant again

This is the reason using that memory outside the function is illegal (thanks @Eugene) when trying to access that memory (integer i in your case)

Upvotes: 0

Related Questions