d0rmLife
d0rmLife

Reputation: 4250

Am I losing information with this printf()?

In Expert C Programming, there is an exercise on page 146 that is supposed to illustrate how a typical Unix OS allocates various segments of an a.out file into various memory segments for execution.

The "starter" code is:

main () {
   int i;
   printf("The stack top is near %#X\n", &i);
}

The compiler warns, but does not error, the use of %X with &i:

warning: format ‘%X’ expects argument of type ‘unsigned int’, but argument 2 has type ‘int *’ [-Wformat]

As a newcomer to memory layouts and hex addresses, I am just wondering if the recommended formatting is not representing the desired information in full? I searched around but couldn't find anything definitive--for instance, I read about using the %p format cue, but it wasn't clear if that was necessary for this case.

Also, it seems doubtful that this sacred C book would make such an error, so I assume it is an extraneous warning for this use case, but I would like to be sure.

Upvotes: 0

Views: 103

Answers (1)

ouah
ouah

Reputation: 145829

   int i;
   printf("The stack top is near %#X\n", &i);

This is undefined behavior. X conversion specifier requires an argument of type unsigned int but &i is of type pointer to int. C does not require an implementation to abort translation in case of undefined behavior but an abort of translation is allowed by C.

To print a pointer value use p conversion specifier:

   int i;
   printf("The stack top is near %p\n", (void *) &i);

Upvotes: 2

Related Questions