2
#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?

2
  • 2
    Node that the %u format specifier for printf expects an unsigned int argument. To print a void * pointer (you need to cast to be correct) use %p. Mismatching format specifier and argument type leads to undefined behavior. Commented Mar 23, 2021 at 7:23
  • 1
    Your pointer will always point to released memory block and will never be valid. Commented Mar 23, 2021 at 7:33

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

-1
printf("%p",&p);

You will get the output.

1 Comment

You're printing the address of p, not the address that was returned from the function call.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.