-1

I am using 64 bit gcc compiler on a intel machine to compile following code

void main(void) {
    unsigned long L = 1, R = "123";
    printf("%s %lu %lu", "1st",L, R);
    printf("%s %d %s", "2nd", L, R);
}

I get following output

1st, 1, 4205913

2nd, 1, 123

my confusion is that when I take %lu what is this number 4205913 while when I take %s "123" is printed correctly.

Community
  • 1
  • 1
prattom
  • 1,625
  • 11
  • 42
  • 67

1 Answers1

2

The reason that 123 gets printed correctly is a coincidence: it happens that in your architecture an address can fit into unsigned long. This is by no means a guarantee, so what you see is undefined behavior that simply "went your way".

The standard defines an integral type uintptr_t that is guaranteed to be capable of holding a pointer, though. Using this type with appropriate casting would let you store a pointer in a non-pointer variable, and avoid undefined behavior.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523