Fun with UB in C: returning uninitialized floats

The average C/C++ programmer's intuition says that uninitialized variables are fine as long as you don't depend on their values.

A more experienced programmer probably suspects that uninitialized variables are fine as long as you don't access them. That is, computing c=a+b where b is uninitialized is not harmless even if you never use c. That's because the compiler could, say, optimize away the entire block of code surrounding c=a+b under the assumption that c=a+b, where b is proven to be always uninitialized, is always undefined behavior (UB). And if it's UB, the only way for the program to be correct is for this code to be unreachable anyway. And if it's unreachable, why waste instructions translating any of it?

However, the following code looks like it could potentially be OK, doesn't it?

float get(obj* v, bool* ok) {
  float c;
  if(v->valid) {
    *ok = true;
    c = v->a + v->b;
  else {
   *ok = false; //not ok, so don't expect anything from c
  return c;

Here you return an uninitialized c, which the caller shouldn't touch because *ok is false. As long as the caller doesn't, all is well, right?

Well, it turns out that even if the caller does nothing at all with the return value – ever, regardless of *ok – the program might bomb. That's because c could be initialized to a singaling NaN, and then say on x86, when the fstp instruction is used to basically just get rid of the return value, you get an exception. In release mode but not in debug mode, some of the time but not all the time. This gives you this warm, fuzzy WTF feeling when you stare at the disassembled code. "Why is there even a float here in the first place?!"

How much uninitialized data is shuffled around by real-world C programs? A lot, I wager – likely closer to 95% than to 5% of programs do this. Otherwise Valgrind would not go to all the trouble to not barf on uninitialized data until the last possible moment (that moment being when a branch is taken based on uninitialized data, or when it's passed to a system call; to not barf then would require some sort of a multiverse simulation approach for which there are not enough computing resources.)

Needless to say, most programs enjoying ("enjoying"?) Valgrind's (or rather memcheck's) conservative approach to error reporting were written neither in assembly which few use, nor in, I dunno, Java, which won't let you do this. They were written in C and C++, and most likely they invoke UB.

(Can you touch uninitialized data in C without triggering UB? I seriously don't know, I'm not a language lawyer. Being able to do this is actually occasionally useful for optimization. Integral types for instance don't have anything like signaling NaNs so at the assembly language level you should be fine. But at the C level the compiler might get needlessly clever if it manages to prove that the data is uninitialized. My own intuition is it can never prove squat about data passed by pointer because of aliasing and so I kinda assume that if I get a buffer pointing to some data and some of it is uninitialized I can do everything to it that I could in assembly. But I'm not sure.)

What a way to make a living.




#1 whitequark on 06.30.15 at 6:54 pm

Integral types actually have an equivalent of signaling NaN on IA64, which IIRC was taken into consideration by the C workgroup.

#2 Yossi Kreinin on 06.30.15 at 7:05 pm

Only in registers, right? It's not like they tag every 8b pixel in an image as "a number" as opposed to "not a number", do they? So there's a substantial grey area here in practice (int local[3] might land in registers whereas int local[256] probably won't, etc.), and say malloced ununitialized bytes are always OK. I wonder if the C standard left the option to touch these without getting hosed or did they "make it simple" and said theoretically you're hosed with any type, anywhere. (Intuitively I'd assume they did the latter…)

#3 FUZxxl on 07.01.15 at 9:42 am

Compilers don't need to use fstp to get rid of an FPU register. They can instead use the ffree ; fincstp combination or even the undocumented ffreep instruction for that.

#4 saarni on 07.01.15 at 10:36 am

As whitequark pointed out, integral values may have "signaling NaN" equivalents: trap representations.

"Any type (except unsigned char) may have trap representations, but no type is required to have them."

Hence reading uninitialized automatic storage integral variable may contain a trap.

#5 LG on 07.01.15 at 11:35 am

I'm not following, what would this trap representation look in like in practice? You mean that the compiler would generate an "int3" (or something like that) instead of the actual uninitialized int read?

#6 Mark on 07.01.15 at 1:06 pm

The real language lawyers hang out on Stack Overflow:

The short answer is that for once, C is saner than you would expect. If you ever take the address of a variable, and the type in question has no scary values like signaling NaNs, then the behavior is well defined: you merely have to contend with assembly-like behavior. (I did not know this five minutes ago! Your blog post made me learn something!) If you want a long answer, go read the top answer on Stack Overflow, or even the top. But the upshot of all this is that the following awesome trick is actually legal C:

For those who have not seen it and are wondering whether it's worth following the link: it's a very simple data structure that uses uninitialized memory to achieve O(1) time for an operation that a naïve implementation would use linear time for. (It's possible to get O(1) time without resorting to uninitialized memory by using a hash table, but that takes work to implement. This is easier to code and runs faster.)

#7 Matthew Fernandez on 07.01.15 at 2:14 pm

I suspect the answer to your final doubt depends on how clever your compiler is at inter-procedural analysis and how much visibility it has within the current translation unit. Of course this always triggers UB in the technical sense, so while you might get away with it you probably shouldn't do it.

#8 hudson on 07.01.15 at 9:42 pm

Minor typo: "c = v->a + b->b;" should probably be "c = v->a + v->b;"

#9 Yossi Kreinin on 07.02.15 at 8:36 am

Thanks – fixed

#10 Yossi Kreinin on 09.15.15 at 7:23 pm


#11 free gg hack on 05.15.19 at 5:58 pm

Respect to website author , some wonderful entropy.

#12 Thad Fulmore on 05.17.19 at 2:39 pm

Appreciate the site– extremely informative and lots to explore!

#13 strucid hacks on 05.28.19 at 10:30 am

Good Morning, google lead me here, keep up great work.

#14 Thad Bartone on 06.05.19 at 7:23 pm

I more or less share your opinion on this subject and look forward to upcoming posts and comments here at Keep up the good work!

#15 how to crack fortnite accounts on 06.17.19 at 5:53 am

I love reading through and I believe this website got some genuinely utilitarian stuff on it! .

#16 dig on 06.18.19 at 11:05 am

The use of uninitialized variables is similar to the use of uninitialized memory and can lead to the various kinds of errors in the course of program operation.

#17 nonsense diamond key generator on 06.21.19 at 9:22 am

Your article has proven useful to me.

#18 dissertations proofreading service go to this site on 06.27.19 at 3:44 pm

Unfortunately, most programs cannot be fully utilized due to the fact that we were completely unable to learn how to use all the necessary features.

#19 cryptotab hack script free download on 06.29.19 at 3:36 pm

Cheers, i really think i will be back to your site

#20 cheat fortnite download no wirus on 07.01.19 at 8:55 pm

Your website has proven useful to me.

#21 cyberhackid on 07.03.19 at 8:25 pm

Yeah bookmaking this wasn’t a risky decision outstanding post! .

#22 prison life hack download on 07.04.19 at 8:27 am

Great, yahoo took me stright here. thanks btw for post. Cheers!

#23 seo tools on 07.04.19 at 2:14 pm

Parasite backlink SEO works well :)

#24 subbot on 07.04.19 at 8:15 pm

You got yourself a new rader.

#25 open dego on 07.05.19 at 8:30 am

Found this on MSN and I’m happy I did. Well written website.

#26 Otis Suzuki on 07.06.19 at 10:19 am

The next phase of the puzzle is to decipher the order of the pyramid. This is your third secret clue! 517232125

#27 RebAbsola on 07.09.19 at 3:01 am

Cephalexin And Diabetes [url=]pastillas levitra[/url] Amoxicillin Good For Prosthesis

#28 ellen_betsy on 07.14.19 at 2:01 am

Thank you for the great read!

#29 Lesangent on 07.14.19 at 3:02 pm

Amoxicillin And Abnormal Menstual Cycles Kamagra Sabores Comprar Veterinary Keflex [url=]viagra[/url] Prix Xenical Espagne Cialis Hipertensos

#30 xxx latex online on 07.15.19 at 2:12 am

some great ideas this gave me!

#31 legalporno free on 07.16.19 at 12:04 am

great advice you give

#32 Valentin Wooster on 07.18.19 at 12:41 pm

Mr.s Fister, this message is your next bit of info. Feel free to message the agency at your earliest convenience. No further information until next transmission. This is broadcast #8277. Do not delete.

#33 victoria_june on 07.19.19 at 1:50 am

you are a great writer!

#34 Buy Drugs Online on 07.19.19 at 2:53 am

This blog is amazing! Thank you.

#35 date cougr on 07.23.19 at 10:44 pm

I am 43 years old and a mother this helped me!

#36 dawte cougar on 07.23.19 at 11:28 pm

I am 43 years old and a mother this helped me!

#37 dqte cougar on 07.23.19 at 11:45 pm

I am 43 years old and a mother this helped me!

#38 on 07.24.19 at 6:37 pm

Good post. I learn something totally new and challenging on websites I stumbleupon every day.

It’s always exciting to read content from other writers and
practice something from other web sites.

#39 on 07.24.19 at 7:52 pm

Hello there! I could have sworn I’ve been to your blog before but after browsing through some
of the posts I realized it’s new to me. Anyhow, I’m certainly
happy I discovered it and I’ll be book-marking it and checking back regularly!

#40 Lesangent on 07.26.19 at 12:45 am

Medicament Propecia Priligy Dapoxetina Italia [url=]viagra[/url] Finasteride Proscar Propecia Profile Propecia Sale Drugstore

#41 123Movies on 08.30.19 at 5:59 am

Very nice post. I just stumbled upon your blog and wanted to say that I’ve really enjoyed browsing your blog posts. After all I’ll be subscribing to your rss feed and I hope you write again very soon!

#42 Fmovies on 08.30.19 at 6:01 am

Ahaa, its nice dialogue on the topic of this post at this place at this website, I have read all that, so now me also commenting here.

#43 YesMovies on 08.30.19 at 6:01 am

We all talk a little about what you should talk about when is shows correspondence to simply because Maybe this has much more than one meaning.

#44 SolarMovies on 08.30.19 at 6:02 am

Hello there, just became alert to your blog through Google, and found that it is truly informative. I’m going to watch out for brussels.I will be grateful if you continue this in future.A lot of people will be benefited from your writing. Cheers!

#45 Roku.Com/Link on 09.13.19 at 10:36 am

This blog is amazing! Thank you.

#46 roku.comlink on 09.23.19 at 11:12 am

Roku is a package of entertainment, where user can stream for unlimited movies, shows, web series, news, cartoon and many more programs.

#47 on 09.30.19 at 12:06 pm

Hulu provides the simplest way to stream entertainment to your TV. On your terms. With thousands of available channels. We provide information regarding Hulu Activation Code. To activate a new Hulu account using an existing email account and you can stream television shows and movies from the Hulu site using the Hulu activation link.

#48 Malwarebytes for mac on 09.30.19 at 12:07 pm

Malwarebytes is an anti-malware software for Microsoft Windows, macOS, Android, and iOS that finds and removes malware from computer. Malwarebytes is a better replacement for an antivirus. To download and install Malwarebytes on your Mac device, Open Internet browser and search for Malwarebytes for Mac.

#49 on 09.30.19 at 12:07 pm is the only security solution which can protect your system from viruses, worms, malware threats. Get Webroot safe today & install on your system and say goodbye to viruses.

#50 on 11.06.19 at 12:25 pm

Im thankful for the blog article.Really thank you

#51 cleaning services in dubai on 11.06.19 at 3:32 pm

Some great benefits of hiring a specialist house preserving service are usually numerous. And lots of times they will out ponder the downsides. Yes that costs funds. But just how valuable can be your time? Some would certainly wager the period is the harder important product. For the individuals there are usually housekeepers offered to help take back more than it. It could be fantastic to own more hours inside the day. But it's not going to happen whenever soon. And possessing even a single extra hour or so sometimes is greater than its fat in rare metal.

#52 on 11.15.19 at 9:40 am

We find lots of learning after reading this very useful article .

#53 MB-210 practice test exam on 12.09.19 at 10:56 am

Nice Post

#54 Fix Roku Error Code 001 Instantly –Call +1 844-756-1728 on 12.10.19 at 9:13 am

Facing Roku Error Code 001? Means you didn’t Activate Roku correctly, for Roku Activation you can dial our Customer Service Number Roku at US/Canada Toll-Free: +1 844-756-1728 and get instant help from our experts for Roku Com/Link Activation.

#55 Huawei Mate 20 Pro Mobile Phone Price in Sri Lanka on 12.17.19 at 6:30 pm

You finished sure dependable focuses there. I completed a pursuit regarding the matter and located about all and sundry will concur together with your blog

#56 mailjet nanogramme on 12.18.19 at 1:02 am

I found your site perfect for me. It comprises of great and helpful posts. I've perused a considerable lot of them and furthermore got such a great amount from them. I would say, you do the genuinely amazing.Truly i'm intrigued out of this distribute

#57 créer une application nanogramme on 12.18.19 at 10:55 pm

You have done a great job. I will definitely dig it and personally recommend to my friends. I am confident they will be benefited from this site

#58 agence digitale on 12.21.19 at 11:04 pm

Thanks for ones marvelous posting! I genuinely enjoyed reading it, you are a great author. I will be sure to bookmark your blog and may come back very soon. I want to encourage you to definitely continue your great job, have a nice weekend.

#59 agence web paris nanogramme on 12.24.19 at 4:26 pm

Just pure brilliance from you here. I have never expected something less than this from you and you have not disappointed me at all. I suppose you will keep the quality work going on.

#60 on 12.26.19 at 1:14 am

Amazing, extraordinary, I was thinking about how to fix skin break out normally. what's more, found your site by google, took in a ton, presently i'm somewhat clear. I've bookmark your site and furthermore include rss. keep us refreshed.

#61 on 12.26.19 at 6:19 am

AVG is the one of best antivirus which protects your computer and network from bad infection and threats. AVG now includes real-time security updates, scans for both malware and performance issues, and even catches malicious downloads before they reach your PC. User can Install AVG Antivirus on their computer to protect thier computer and network…

#62 on 12.26.19 at 6:21 am

AVG AntiVirus is a family of antivirus software developed by AVG Technologies, a subsidiary of Avast. It is available for Windows, macOS and Android. AVG ensuring your safety and security online. In AVG features, most of the common functions available in modern antivirus and Internet security programs, including periodic scans. AVG Online Shield also ensures the safety of exchanging files via instant messengers and VoIP clients.

#63 on 12.26.19 at 6:22 am

AVG line-up combines effective malware eradication with fast scans and just about every security feature you could wish for. Simply activate AVG license and install AVG on your system to keep your system protected.

#64 on 12.26.19 at 6:23 am

It is very helpful to secure your device and it is very light weighted antivirus product.
Webroot secure anywhere offers a user-friendly interface which provides several functions & they all work together to make a system protected. To activate Webroot go to
Webroot security is a great antivirus program, which amazingly lightweight tool with accurate URL blocking and powerful bonus features.

#65 panda antivirus on 12.26.19 at 6:24 am

Panda Free Antivirus is fast and free, boasts the top score in real-world protection, and offers a USB drive cleaner. Panda offers an extra layer of security against malware that tries to access sensitive user data for malicious purposes. Data Shield allows the user to define the location of data to protect as well as the access permissions of installed programs. Real-time protection against all types of malware and spyware. Schedule periodic scans and/or scan your computer on demand.

#66 on 12.26.19 at 12:52 pm

Install and Activate Your Xfinity Self-Install Kit.This record provides resources to help you through installation and activation of the equipment and services contained in your Xfinity Self-Install Kit.
To set up your services, start by learning about the equipment included on your Xfinity Self-Install Kit. Then videos that will walk you can be watched by you.
We supply you with a step-by-step guide to activating your services. To get started, learn the different approaches to activate your Self-Install Kit apparatus.
Installation and Immediately Following a Transfer
Are you a present Xfinity customer who recently transferred? Can you choose your equipment with you? If that's the case, you will need to follow along with the instructions. Learn how to set up and activate your providers after you move.

#67 on 12.26.19 at 1:24 pm

Hi, i think that i saw you visited my web site thus i came to “return the favor”.I am
trying to find things to improve my web site!I suppose its ok to use
a few of your ideas!!

#68 site marchand nanogramme on 12.27.19 at 11:36 pm

Very nice content thank you very much for writing such an interesting article on this topic. This has really made me think and I hope to read more.

#69 site vitrine nanogramme on 12.28.19 at 4:21 pm

Just pure brilliance from you here. I have never expected something less than this from you and you have not disappointed me at all. I suppose you will keep the quality work going on.

#70 agence digitale paris on 12.29.19 at 1:08 pm

I found your site ideal for me. It contains extraordinary and supportive posts. I am pretty well pleased with your good work. Looking to read your next post.

#71 nanogramme on 12.31.19 at 12:00 am

Thankful for granting such magnificent information to us. Kaspersky Login is a basic, clear and straightforward procedure. Regardless, once in a while you may get the Kaspersky login botch. This screw up can be appeared considering a couple of reasons.

#72 site e commerce nanogramme on 12.31.19 at 1:33 pm

Amazing knowledge and I like to share this kind of information with my friends and hope they like it they why I do.

#73 créer une application android nanogramme on 12.31.19 at 7:14 pm

I am pretty much pleased with your good work. Very nice content thank you very much for writing such an interesting article on this topic.

#74 créer une application mobile nanogramme on 01.02.20 at 1:12 pm

This is a wonderful article, Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more … good luck.

#75 application web nanogramme on 01.02.20 at 10:49 pm

I’m happy I located this blog! From time to time, students want to cognitive the keys of productive literary essays composing. Your first-class knowledge about this good post can become a proper basis for such people.

#76 creation site e commerce nanogramme on 01.03.20 at 12:44 am

Appreciative for giving such wonderful data to us. Kaspersky Login is an essential, clear and direct method. In any case, on occasion you may get the Kaspersky login mess up. This botch can be showed up thinking about two or three reasons.

#77 sous traitance web seopublissoft on 01.03.20 at 11:48 pm

You have done a great job. I will definitely dig it and personally recommend to my friends. I am confident they will be benefited from this site

#78 Latest HTC Mobile phone price in Malaysia on 01.07.20 at 1:19 pm

precise stuff! Congrats for making it viable for growing this blog. i'm strongly trust your posting cloth and need to want to mention
thank you for making this put up right here

#79 벳 365 on 01.09.20 at 5:42 pm

I need to a large portion of the facts, I must guarantee when I loved, when I would really like extra facts recognized with that,
on account that it's especially superb., recognize it about uncovering

#80 Latest HTC Mobile phone price in Singapore on 01.14.20 at 7:21 pm

hello, I discover scrutinizing this text a pride. it's miles distinctly useful and fascinating and specially envisioning analyzing a
more noteworthy degree of your paintings

#81 air conditioning service and repairs on 01.23.20 at 5:33 am

Marvelous posting this is from you. I am genuinely and truly eager to scrutinize this brilliant post. You've really charmed me today. I believe you'll continue doing all things considered!

#82 행진 on 01.23.20 at 3:27 pm

I’m excited to discover this page. I want to to thanks for ones time for this specially incredible study!! I in reality simply
preferred each part of it and that i additionally have you ever saved to fav to study new records in your site

#83 토토사이트추천 on 01.25.20 at 1:04 am

i love the way you write and proportion your area of interest! Very interesting and one-of-a-kind! keep it coming!

#84 토토록스 정보 on 01.28.20 at 4:26 pm

Your blogs is so desirable further serviceable It appoints me befall retreat encore. i am capable of
instantly hold close your rss feed to live knowledgeable of any updates.

#85 토토사이트 on 01.29.20 at 5:57 pm

I commonly visit this web page to observe the activities and works and from time to time for belongings. although,
it's been a while which you have shared a few report approximately maximum current or up and coming activities

#86 먹튀 사이트 on 01.31.20 at 2:14 am

that is very terrific and very Informative Artical we get alot of Informations from this artical we surely respect your
crew paintings hold it up and preserve posting this sort of informative articles

#87 spojoy on 02.02.20 at 11:11 pm

Wow! Such an incredible and beneficial submit that is. I virtually really love it. it is so appropriate and so
notable. i am just amazed. i hope which you retain to do your work like this in the destiny additionally.

#88 Perth Doggy Daycare on 02.06.20 at 7:12 pm

Heavenly posting this is from you. I am really and genuinely anxious to examine this splendid post. You've truly enchanted me today. I accept you'll keep doing taking everything into account!

#89 financial advisor NYC on 02.09.20 at 3:42 pm

I just couldn't leave your web site before disclosing to you that I actually delighted within the pinnacle quality statistics you
gift for your visitors? could be again once more frequently to determine the reputation of latest posts.

#90 Rope lights on 02.09.20 at 5:54 pm

I admire this website in this is very beneficial content and really informative web page click on here

#91 Insurance Broomfield CO on 02.11.20 at 4:50 pm

I in reality glad observed this internet site finally. in reality informative and inoperative, thank you for the post and
effort! Please preserve sharing extra such weblog.

#92 Disc Golf Putters on 02.13.20 at 7:09 pm

wonderful posting this is from you. i'm definitely and certainly eager to scrutinize this super post. you have
honestly charmed me these days. I believe you'll maintain doing all things considered

#93 Nasal Dilator on 02.14.20 at 12:47 am

Extraordinary post.This isn't really awful post and gives full data. I like to examine this post considering I met such a great deal of new genuine elements concerning it really.Thanks loads. I bookmark your web log because of I found bewildering data on your web log, Thanks for sharing.