1

When I enter 'A', below code outputs(my editor Visual Studio Express 2012) ,

A 65 65 65

but this example given in Deitel C How to Program output is different such as:

A -13247 -858993599 -858993599

Why?

#include <stdio.h>

union dummy {
  char c;
  short s;
  int i;
  long l;
} a;


int main(void) {

    printf("Enter a character\n");
    scanf("%c", &a.c);

    printf("%c printed as a char is %c.\n", a.c, a.c);
    printf("%c printed as a short is %hd.\n", a.c, a.s);
    printf("%c printed as an int is %d.\n", a.c, a.i);
    printf("%c printed as a long is %ld.\n", a.c, a.l);

    getch();
    return 0;
}
Jens
  • 69,818
  • 15
  • 125
  • 179
Lyrk
  • 1,936
  • 4
  • 26
  • 48
  • 3
    @EdHeal: No reason to be rude. He is just learning C and trying to reproduce the output from a sample in his learning book. I think that is totally legitimate. And the question is not so bad, there are two reasons that interfere, not everybody sees that (and the learning questioner does not need to to so). – Werner Henze Oct 31 '13 at 08:41

1 Answers1

3

The compilers seem to behave differently and both samples have been run on different machines with different endianess.

MSVC is initializing a with zeroes. Then you overwrite only c, the rest is still zero. Because of the hardware endianess c is stored at the low byte of s, which is also the low word of i and l. So MSVC outputs A 65 65 65 ('A'==65==0x41).

The compiler used in Deitel C How to Program initializes a to 0xcccccccc and only overwrites the memory of a.c. Because of the different endianess c is the high byte of s which is the high word of i and l. If you print the values as hex, you can see that: A cc41 cccccc41 cccccccc41.

The reason for the different initialization might be, that some compilers initialize variables to a defined pattern (here 0xcc) so that you can easily detect if you are accessing an uninitialized variable or memory block. Normally this is only done when you compile your program in debug mode. In this case sometimes also malloc and free are changed so that not only malloc initializes memory to a defined pattern, but also free overwrites the memory before actually freeing it. So if you keep a dangling pointer and access the freed memory, you can easily see from the content that you are accessing freed memory.

Werner Henze
  • 16,404
  • 12
  • 44
  • 69
  • You're wrong. MSVC compiler also fills uninitialized zones to 0xCC in debug mode http://stackoverflow.com/questions/370195/when-and-why-will-an-os-initialise-memory-to-0xcd-0xdd-etc-on-malloc-free-new/370362#370362 – phuclv Oct 31 '13 at 08:46
  • 1
    @LưuVĩnhPhúc: I know. But if you read the question, then you'll see that *in this case* MSVC did not initialize to 0xcc. But good point, I'll add that to my answer. – Werner Henze Oct 31 '13 at 08:52