sind
sind

Reputation: 41

How can a function returning the address of the variable return zero?

#include<stdio.h>

int *addressof();

int main()

{               
    int *p=addressof();
    printf("%u",p);
    return 0; 
}            
int *addressof()
{
    int x=9;
    
    return &x;
}

Output:

0

Can the address of the variable be zero? Is it possible?

Upvotes: 2

Views: 299

Answers (3)

the busybee
the busybee

Reputation: 12610

Note: This is an addition to this answer, which covers some reason why you got zero.

Depending on your target system and its compiler, of course a variable can have an address of zero. This is the case for example on MCS51 microcontrollers, where (external) RAM starts at 0 and is used for variables. Unfortunately in that system NULL is also defined as a zero pointer, which makes common usages difficult.

Upvotes: 3

Simson
Simson

Reputation: 3559

The code you have written have undefined behavior as it returns the address of a local variable which will have been released when the function returns. In this case the compiler is can choose to optimize it and return 0.

If you change the variable to a static instead the address you return will be valid

int *addressof()
{
    static int x=9;
    
    return &x;
}

Check the warnings from your compiler, the second problem is, the size of a pointer is not necessarily the same as unsigned long, replace "%u" with "%p" in the printf.

Upvotes: 5

H Hasan
H Hasan

Reputation: 55

printf("%p",&p);

You will get the output.

Upvotes: -1

Related Questions