Re: libc/printf bug



"bill pursell" <bill.pursell@xxxxxxxxx> writes:

The following code exhibits unexpected behavior. Either it's
a bug in libc, or the author (me) is blind as a bat. Am I missing
something here, or is something horribly wrong? It appears
that printf is mangling the address unless the second argument
gets cast. I don't see that the cast should have any effect at all
on the output. Any thoughts?

[tmp]$ cat printf_bug.c


int
main()
{

float a=0;

printf("%p\n", &a);

The above is mostly fine, although to be portable outside of Linux,
you might wish to cast &a to (void*).

printf("%x %p\n", a, &a);

This is flat wrong.

The "%x" conversion specifer tells printf() that you've given it an
unsigned int. You've actually given it a double (the float automatically
gets converted to a double when you use it in a variadic function*
like printf(). So, you've accidentally(?) just lied to printf() about
what you're going to pass to it. All kinds of funky stuff could result.

* variadic functions are functions that take a variable number of
arguments.

To use the %x specifier, you should cast to (unsigned int).

printf("%x %p\n", (int)a, &a);

This is better, and pretty likely to work on Linux. For portability
and just all-around correctness, you should cast to (unsigned int), as
I explained earlier.

In general when using printf() and the like, if you're not passing it
a variable that is /exactly/ the type that printf() expects, be sure
and cast it. The exceptions would be chars and shorts, which get
promoted to ints before being passed to printf(); and floats, which
get promoted to doubles.

HTH,
Micah
.



Relevant Pages

  • Re: pointer
    ... I think you need %02hhx there, or cast pto (unsigned int). ... Technically, yes, but it's also worth pointing out that implementations ... corresponding unsigned type, and vice versa, so for printf not to accept ...
    (comp.lang.c)
  • Re: why the printf is not typecasting the int to float
    ... The printf() family uses the variadic function interface (see ... 'int') must match exactly the type specified in the format string ...
    (comp.lang.c)
  • Re: is fstat or printf error?
    ... The error occurs because printfdoes _not_ cast ... the to int. ... printf, however, examines the first parameter (the ... '%d' in the format string. ...
    (comp.os.linux.misc)
  • Re: pointers chainging in a function call?
    ... snip ... ... He should cast the pointer arguments to printf to ...
    (comp.lang.c)
  • Re: problem incrementing my variable
    ... int i = 42; ... which WILL need the cast. ... both printf calls are incorrect. ... Unless the format string is computed at run time and imposed by ...
    (comp.lang.c)

Quantcast