Re: libc/printf bug
- From: Micah Cowan <micah@xxxxxxxxxx>
- Date: Tue, 28 Feb 2006 00:05:58 GMT
"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
.
- References:
- libc/printf bug
- From: bill pursell
- libc/printf bug
- Prev by Date: Re: libc/printf bug
- Next by Date: Re: prevent multiple start of app
- Previous by thread: Re: libc/printf bug
- Next by thread: Re: libc/printf bug
- Index(es):
Relevant Pages
|