[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
|
|
Subscribe / Log in / New account

Oh, forgot to say...

Oh, forgot to say...

Posted May 24, 2011 10:19 UTC (Tue) by khim (subscriber, #9252)
In reply to: It's different viewpoints... by etienne
Parent article: What Every C Programmer Should Know About Undefined Behavior #3/3

Same for debugging, I may want to display some binary values as unsigned in hexadecimal even if I know that is a float (so a dirty cast), to see if I had a memory overflow and in fact this float contains a string...

Note that ANSI C standard does not consider this use case important enough to you can not ever convert print float as hex (it's even explained in wikipedia article) without triggering undefined behavior - but GNU C gives you such ability if you'll use union. This is enough for debugging, but please don't leave it in your program afterwards: GCC is not the only compiler in the world, you don't want to see your program broken later.


to post comments

Oh, forgot to say...

Posted May 24, 2011 18:35 UTC (Tue) by jrn (subscriber, #64214) [Link] (2 responses)

Wouldn't a loop to access the internal representation of a float through a pointer to char produce implementation-defined behavior, rather than nasal demons? On the other hand, reading through a pointer to unsigned int is problematic, of course.

Yes, that's true...

Posted May 25, 2011 5:01 UTC (Wed) by khim (subscriber, #9252) [Link] (1 responses)

Ah, my bad. Sure, but the temptation is very high to use conversion to int because they are of the same size - and this is impossible to do even if you use two transitions like (int *)(char *)pf.

The only way to portably and correctly do that is via memcpy - and with current crop of the compilers it's quite efficient too (both memcpy and pointers will be elided), but this is counter-intuitive if you don't know about undefined behaviors and still think that C is high-level assembler.

Yes, that's true...

Posted May 25, 2011 5:19 UTC (Wed) by jrn (subscriber, #64214) [Link]

Even memcpy is not portable to platforms where sizeof(float) != sizeof(int). :)

A rough and incomplete rule of thumb about aliasing rules is that constructs that would be portable given how alignment and size varies from platform to platform are likely to be permitted.


Copyright © 2025, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds