When this program is compiled and executed on an x86-64 Linux system, it prints the string 0x48\n and terminates normally, even though function p2 never initializes variable main. Can you explain this?

Respuesta :

Answer:

I get 0x55 and this the linking address of the main function.

use this function to see changes:

/* bar6.c */

#include <stdio.h>

char main1;

void p2()

{

printf("0x%X\n", main1);

}

Output is probably 0x0

you can use your original bar6.c with updaated foo.c

char main;

int main() // error because main is already declared

{

  p2();

   //printf("Main address is 0x%x\n",main);

  return 0;

}

Will give u an error

again

int main()

{

  char ch = main;

  p2(); //some value

  printf("Main address is 0x%x\n",main); //some 8 digit number not what printed in p2()

  printf("Char value is 0x%x\n",ch); //last two digit of previous line output

  return 0;

}

So the pain in P2() gets the linking address of the main function and it is different from address of the function main.

Now char main (uninitialized) in another compilation unit fools the compiler by memory-mapping a function pointer on a char directly, without any conversion: that's undefined behavior. Try char main=12; you'll get a multiply defined symbol main...

Explanation:

ACCESS MORE