Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does %d show two different values for *b and *c in the code [b and c points to same address]

Tags:

c

pointers

Consider the Code below

{
float a=7.999,*b,*c;
b=&a;c=b;
printf("%d-b\n%d-c\n%d-a\n",*b,*c,a);
}

OUTPUT:

-536870912-b
1075838713-c
-536870912-a

I know we are not allowed to use %d instead of %f, but why does *b and *c give two different values? Both have the same address, can someone explain? I want to know the logic behind it

like image 449
Nithin Jose Avatar asked Apr 05 '14 16:04

Nithin Jose


3 Answers

Here is a simplified example of your ordeal:

#include <stdio.h>
int main() {
  float a=7.999, b=7.999;
  printf("%d-a\n%d-b\n",a,b);
}

What's happening is that a and b are converted to doubles (8 bytes each) for the call to printf (since it is variadic). Inside the printf function, the given data, 16 bytes, is printed as two 4-byte ints. So you're printing the first and second half of one of the given double's data as ints.

Try changing the printf call to this and you'll see both halves of both doubles as ints:

  printf("%d-a1\n%d-a2\n%d-b1\n%d-b2\n",a,b);

I should add that as far as the standard is concerned, this is simply "undefined behavior", so the above interpretation (tested on gcc) would apply only to certain implementations.

like image 80
ooga Avatar answered Sep 26 '22 14:09

ooga


There can be any number of reasons.

The most obvious -- your platform passes some integers in integer registers and some floating point numbers in floating point registers, causing printf to look in registers that have never been set to any particular value.

Another possibility -- the variables are different sizes. So printf is looking in data that wasn't set or was set as part of some other operation.

Because printf takes its parameters through ..., type agreement is essential to ensure the implementation of the function is even looking in the right places for its parameters.

You would have to have deep knowledge of your platform and/or dig into the generated assembly code to know for sure.

like image 35
David Schwartz Avatar answered Sep 22 '22 14:09

David Schwartz


Using wrong conversion specification invokes undefined behavior. You may get either expected or unexpected value. Your program may crash, may give different result on different compiler or any unexpected behavior.

C11: 7.21.6 Formatted input/output functions:

If a conversion specification is invalid, the behavior is undefined.282) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

like image 30
haccks Avatar answered Sep 26 '22 14:09

haccks