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.
93 comments ↓
Integral types actually have an equivalent of signaling NaN on IA64, which IIRC was taken into consideration by the C workgroup.
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…)
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.
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.
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?
The real language lawyers hang out on Stack Overflow:
http://stackoverflow.com/questions/11962457
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:
http://research.swtch.com/sparse
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.)
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.
Minor typo: "c = v->a + b->b;" should probably be "c = v->a + v->b;"
Thanks – fixed
test
Respect to website author , some wonderful entropy.
Appreciate the site– extremely informative and lots to explore!
Good Morning, google lead me here, keep up great work.
I more or less share your opinion on this subject and look forward to upcoming posts and comments here at yosefk.com. Keep up the good work!
I love reading through and I believe this website got some genuinely utilitarian stuff on it! .
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.
Your article has proven useful to me.
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.
Cheers, i really think i will be back to your site
Your website has proven useful to me.
Yeah bookmaking this wasn’t a risky decision outstanding post! .
Great, yahoo took me stright here. thanks btw for post. Cheers!
Parasite backlink SEO works well :)
You got yourself a new rader.
Found this on MSN and I’m happy I did. Well written website.
The next phase of the puzzle is to decipher the order of the pyramid. This is your third secret clue! 517232125
Cephalexin And Diabetes [url=http://gnplls.com]pastillas levitra[/url] Amoxicillin Good For Prosthesis
Thank you for the great read!
Amoxicillin And Abnormal Menstual Cycles Kamagra Sabores Comprar Veterinary Keflex [url=http://genericvia.com]viagra[/url] Prix Xenical Espagne Cialis Hipertensos
some great ideas this gave me!
great advice you give
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.
you are a great writer!
This blog is amazing! Thank you.
I am 43 years old and a mother this helped me!
I am 43 years old and a mother this helped me!
I am 43 years old and a mother this helped me!
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.
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!
Medicament Propecia Priligy Dapoxetina Italia [url=http://ordercheapvia.com]viagra[/url] Finasteride Proscar Propecia Profile Propecia Sale Drugstore
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!
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.
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.
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!
This blog is amazing! Thank you.
Roku is a package of entertainment, where user can stream for unlimited movies, shows, web series, news, cartoon and many more programs.
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.
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.
Webroot.com/safe 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.
Im thankful for the blog article.Really thank you
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.
We find lots of learning after reading this very useful article .
Nice Post
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.
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
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
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
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.
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.
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.
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…
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.
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.
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.com/safe
Webroot security is a great antivirus program, which amazingly lightweight tool with accurate URL blocking and powerful bonus features.
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.
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.
Installation
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.
Activation
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.
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!!
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.
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.
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.
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.
Amazing knowledge and I like to share this kind of information with my friends and hope they like it they why I do.
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.
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.
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.
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.
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
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
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
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
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!
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
i love the way you write and proportion your area of interest! Very interesting and one-of-a-kind! keep it coming!
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.
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
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
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.
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!
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.
I admire this website in this is very beneficial content and really informative web page click on here
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.
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
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.