11 ms·
Initialization in C++ is Seriously Bonkers
- ajross 8y ago> [Why is a global variable zero?] Because i has static storage duration, it’s initialized to unsigned zero. Why, you ask? Because the standard says so. No, it's because i lives in an area allocated at the OS level, and OS has to have initialized that memory with something (otherwise you'd have a security bug). The .bss segment has been zeroed, for obvious reasons, since the advent of modern linkage. The explanation is backwards. The reason that stack variables are UNinitialized is (contra the article which thinks it's because the programmer didn't put an initializer in the source code) that memory is on the stack, which is allocated internal to your program and in practice was used previously by some other call for some other purpose. The fact that stack variables are uninitialized by default is actually an intentional feature, not a bug, as it correctly expresses the behavior of the runtime environment. Now, it may not be a good feature, and modern language designs have omitted it (by, let's remember, relying on much better modern compilers to elide all the extra code that would otherwise have been needed to zero out a stack frame!). But it's got nothing to do with the syntax of the language. You can rely on .bss being zero in assembly, and similarly be surprised that stack memory is going to have junk in it.
- lasagnaphil 8y agoI always think C/C++ is not a good first language to teach, because you need to understand some general concepts about computer systems before diving in. Probably more than half of the beginners in their first C class give up when handling pointers/arrays - it's not because the concept is hard, but because they have no idea what the "memory" in the computer actually is and how it works. You're left with a naive analogy of home addresses and phone numbers, but it really doesn't give pointers justice (especially when dealing with arrays and dynamic memory!) Every student learning C should have a basic idea about the stack and the heap, how function calls work, and how assembly code is executed, in order to get the full picture. Anyways, the problem C++ has for beginners is that the language tries to obscure the already hard to understand low-level behavior with high-level concepts (to be fair, that is the language's ultimate goal: to provide a high-level abstraction for low-level code.) So maybe good for your second/third language, but definitely not your first.
- shereadsthenews 8y ago> I always think C/C++ is not a good first language to teach, because you need to understand some general concepts about computer systems before diving in. Some believe that it's important to teach those things about computer systems first. To anyone who knows how the machine works it's pretty obvious why a primitive stack variable is uninitialized: initializing them would cost a store which would in most cases be pointless. People use C and C++ because they want all of the performance the machine has to offer, and usually more. Stuffing the program full of immediate value loads and stores would make it huge and slow. C++ is already cursed with enough pointless stores, for example initializing the buffer of a string just after resize and just before copying something else into the same memory. We don't need more of these things. The author then goes on to complain at length about {} initializers in C++11, which everyone recognizes as problematic, and which has been partially fixed in C++14. This has basically nothing to do with the first part of the article.
- ChrisSD 8y agoI think it's better to teach basic assembly before C. Using memory addresses makes so much more sense in assembly. But for a first language I'd want to use something like Python or Javascript or even a toy language. It simply needs to be something where some basic, high level concepts can be taught without worrying about the details.
- ahartmetz 8y agoYeah, there is really no need to be scared of assembly. It is easy to learn because there is not much to it. Only writing nontrivial programs in assembly is hard, and you don't need to do that to understand what's going on behind the scenes in compiled code.
- a1369209993 8y ago> Only writing nontrivial programs in assembly is hard It's not even really hard, just crushingly tedious and error-prone. You could also write all your programs on 80-column punch cards or with (1)ed, but why bother if there isn't some technical reason why a text editor isn't available?
- amluto 8y ago> The .bss segment has been zeroed, for obvious reasons, since the advent of modern linkage. For your amusement: in the Linux kernel, at least on x86, .bss isn’t initialized when the kernel is loaded. Instead, the kernel memsets it to zero a little later. I don’t know why. Also, because all this stuff predates any concept of security, there is no read-only equivalent of .bss in most systems, meaning that you get suboptimal code for: const int i = 0;
- rabidrat 8y agoThe OS program loader is who allocates pages to .bss and initializes them to zero. In the case of an OS, who would do that initialization? At best it would be the bootloader. Initialization during kernel_init() before using any globals is acceptable too.
- Gibbon1 8y agoHaving seen both sides of this, people are arguing about the proper way to skin a cat. The standard only cares the cat be skinned not how. On OS it's done by the OS for security and performance reasons. One you don't want people to snoop on memory freed from other processes. Two the OS can use the MMU to map in previously zero's pages of memory on demand, so you don't need to actually zero the entire .BSS section on startup. On a bare metal system usually it's done either in assembly (or more cheezy in C) + linker magic.
- jstimpfle 8y agoIt's hard to imagine many situations where you need to give a name to the constant value 0. And think how "optimal" it would be if there were many and we had a read-only BSS! We could cheaply get a huuuge section full of constant zeroes. I think you can in fact realize the idea in PECOFF, by the way. I still need to figure out some aspects to it these days (it seems a bit arcane and maybe Windows doesn't follow the spec very well). But in any case PECOFF has this notion "VirtualSize" (size of section in running program) and "SizeInFile" (size of the prefix of the section that should be filled with contents from the executable file). If SizeInFile is smaller than VirtualSize then the rest of the image gets filled with zeroes I think.
- ori_b 8y ago> No, it's because i lives in an area allocated at the OS level What OS? I don't have one. I have to link in init code to zero sections of ram before my embedded code runs. Sure, it got into the standard because some popular OSes like Unix zero initialized pages, but it's not a universal truth. The reason it's guaranteed in C is because of the spec.
- valarauca1 8y agoNot necessarily true. C89 only requires that static values be initialized. A modern C standard (section: 6.7.8(10)) requires static values be initialized, but what the value is initialized too be _technically_ indeterminate. There is the guide line given that integers must be zero, and pointers be NULL. But if a static storage class isn't consisting of purely integers, pointers, or (fixed sized) structures, arrays, and unions who's elements can recursively reduced to integers or pointers. Then the standard says the initialized value is indeterminate. While relatively straightforward, there is a few gotcha's.
- tom_ 8y agoThe C11 rules for static values are pretty explicit: ``` If an object that has static or thread storage duration is not initialized explicitly, then: - if it has pointer type, it is initialized to a null pointer; - if it has arithmetic type, it is initialized to (positive or unsigned) zero; - if it is an aggregate, every member is initialized (recursively) according to these rules, and any padding is initialized to zero bits; - if it is a union, the first named member is initialized (recursively) according to these rules, and any padding is initialized to zero bits; ''' I think that covers every possible value you can create, and it seems pretty non-indeterminate by my reading.
- pooppaint 8y agoDear lord sounds like you got lost from comp.lang.c. How did it get into the spec? Because Unix did it that way. Just like gets made it into the spec. It’s not like that was some willful good design. The history of C and it’s standarization is inextricably ties to the history of Unix.
- waynecochran 8y agoIn embedded assemblers I have used (TMS34010), the BSS section is uninitialized when the program is loaded (I helped write the OS). When I wrote embedded C, the added C runtime code that executes (before main() is called) zeroes out the BSS section (the OS has nothing to do with it). In other words, it is the C runtime that is responsible for initializing, not the OS.
- ajross 8y agoI think you're the fourth person jumping in to quibble with my "bss is zeroed by the OS" statement by snarking about "Ah hah! But what if you YOU ARE the OS?!". Yeah, I know. I live in that world too. I don't know that it's particularly relevant. The C standard is written to a norm of a Unix userspace environment, and that's clearly where the linked article is working.
- waynecochran 8y agoIt’s the C runtime that zeros it, not the OS. That’s my main point. The OS may initialize too, but that is outside the standard.
- ajross 8y agoOn oddball platforms it might be (though I think there's some quibbling as to whether the C runtime in such an environment is really distinct form "the OS"). It's not on Linux. The .bss segment becomes an anonymous mmap which is zeroed by the kernel when first accessed. Glibc never touches it. (Edit to correct: obviously glibc "touches" .bss because it has its own static variables. But there's no "zero .bss" step in crt0.o)
- monocasa 8y agoI mean, there's probably more shipped units of "oddball systems" than there are of Unix-like multi process systems that have to wipe segments like .bss vracuse of their security model. So it's not like it's some pedantic corner case like you're implying. And there are other parts of the C standard that would just declare 'implementation defined', so the standard doesn't have to say static duration is initialized just because that's what multi process systems do.
- atombender 8y agoI don't think we should pretend that any of this was planned out. The reason the C standard is like it is because it doesn't just specify the best possible version of C that can exist, but because it encodes historical behaviour. It's possible to post-rationalize those decisions, but as I understand it, there's no particular reason why .bss has to be initialized -- it just happens to be the way Unix has worked since forever. With modern static analysis, there's probably no performance benefit to not initializing stack variables that are read before they're written?
- deleted 8y ago[deleted]
- jstimpfle 8y ago> With modern static analysis, there's probably no performance benefit to not initializing stack variables that are read before they're written? Not really relevant because that's a bug. But the common thinking "let's always default-initialize stack variables because the compiler will make it efficient anyway" is clearly "sufficiently smart compiler" thinking. Implicit default initialization will never be 100% as efficient as simply not requiring initialization. Plus, I like the error messages I can get, sometimes, with no default initialization. The compiler can statically detect some uninitialized reads. It cannot do that if all variables are implicitly initialized. In many other cases at least one can be quite certain to experience random crashes that let one track down the bad read rather quickly. In other words, implicitly initializing to zero normally just hides logic bugs. It doesn't make them go away.
- Joky 8y agoNote that clang just got a change to experiment with this: https://reviews.llvm.org/rL349442 https://reviews.llvm.org/rL349442
- jstimpfle 8y agoDoesn't seem to me like a statement that variables should be implicitly initialized. It seems like a workaround around insanity with respect to UB (where compilers fail to notify the programmer that they statically detected a logic bug, and instead go on with compiling, making crazy optimizations based on the wrong assumption that the logic bug was never there).
- ben0x539 8y agoYou're certainly correct, but I don't understand why you're phrasing this as an objection rather than as a rationale for how the language is specified. Personally, I enjoy that the C standard makes a bunch of guarantees that I can use for my reasoning about correctness. Of course I can only get so far reasoning in abstract, language-defined terms and ignoring the execution environment, but where it is sufficient, being able to forget about operating system minutiae is certainly a relief. Since the main thrust of the article is that C++'s language-imposed rules are overly complicated, restricting the perspective to the language specification seems reasonable.
- MaxBarraclough 8y ago> The reason that stack variables are UNinitialized is (contra the article which thinks it's because the programmer didn't put an initializer in the source code) that memory is on the stack, which is allocated internal to your program and in practice was used previously by some other call for some other purpose. It is because the programmer didn't put an initializer into the source code. That's how the language is defined. What you are discussing is the underlying reason the language is defined that way. You are speaking past the author, not pointing out a mistake. The blog post does contain a genuine error relating to this point, though: Any C programmer worth anything knows that this initializes i to an indeterminate value. This is wrong. Reading the variable does not simply give you an indeterminate value, it gives undefined behaviour (something the article never mentions, surprisingly). > that stack variables are uninitialized by default is actually an intentional feature, not a bug, as it correctly expresses the behavior of the runtime environment But it doesn't. Reading an uninitialized local variable gives undefined behaviour, which might not correspond to the behaviour of using any particular garbage value. Anyway, the language is defined that way simply for performance reasons. The risk of undefined behaviour is a considerable downside but was deemed acceptable. > But it's got nothing to do with the syntax of the language. We're talking about the semantics of C. If C were defined such that static integer variables be initialized with 1 rather than 0, that's what would happen, no?
- codeflo 8y agoYou're not wrong, but I think this is a case where knowing the reason for the rules is easier than remembering the actual rules. This is just from personal experience, but for me, remembering what is and isn't initialized in C++ seemed completely arbitrary and insane until I learned more about linking and process startup. YMMV of course.
- MaxBarraclough 8y agoI agree there's a lot of value in understanding hardware/OSs/etc, but it's no substitute for having a solid understanding of C in general. C has much to say on undefined behaviour, and there are no shortcuts - you just have to have a good grasp of the language's dark corners. (Aside: I believe ++i++; is no longer UB in the latest version of the language, but used to be.) On the particular topic of initialization in C/C++, I go with the rule of thumb of be as explicit as possible. Beyond that, I'm not afraid to assign a marker value to a local only to overwrite it soon afterwards. I save myself endless trouble in case my code is buggy, and if it's not, the compiler is likely to elide the first assignment entirely.
- tines 8y agoIn my view this author falls into the camp of people calling C++ a mess because it gives them too much control when they ask for it. One of his examples which he calls "The Abyss": #include <iostream> struct A { A(std::initializer_list<int> l) : i(2) {} A(int i = 1) : i(i) {} int i; }; int main() { A a1; A a2{}; A a3(3); A a4 = {5}; A a5{4, 3, 2}; std::cout << a1.i << " " << a2.i << " " << a3.i << " " << a4.i << " " << a5.i << std::endl; } which outputs: 1 1 3 2 2 he claims to be mysterious but is actually pretty reasonable. In the case of: a1: There is no initializer list in the variable declaration, so ctor 2 is called. a2: An empty initializer list should reasonably behave like a default constructor, and a default constructor should be more efficient than processing an initializer_list, so ctor 2 is called. In general, the constructor with the matching number of arguments and correct types is preferred over initializer_list constructors. Makes sense, being able to specialize on number and type of arguments is more powerful than a design where a single initializer_list ctor invalidates all other ctors. a3: No list, ctor 2 is called. a4: Non-empty init list and no specialized non-init-list ctor, so ctor 1 is called. a5: Several-variable init list and no overriding 3-variable constructor with matching types, therefore ctor 1 is called. Complex? Maybe, but that's what you get with C++: very fine control of program semantics, benefit being expressive libraries. No other language fills this niche that I'm aware of. I agree that C++ isn't a good language to teach in a CS 101 class. But no other single language is good either. The goal of CS 101 is to not make students give up before they get hooked, and that can happen because the material is too challenging or not challenging enough. For people in the former category, give them a scripting language and visual feedback, like Lua + Garrysmod. For the latter, give them assembly, haskell, C, C++ (teaching it like "C with templates" not "C with classes").
- hellofunk 8y agoNot sure where it is but I saw a slide recently from a cpp conference that showed something like 25 different ways to initialize an integer. I wasn't at the conference but I wonder what point the speaker was making.
- kllrnohj 8y ago> C++ is not a language I’d want to teach beginners. At no point in this post was there room for systems programming concepts, discourse on programming paradigms, computational-oriented problem solving methodologies, or fundamental algorithms. This is a ridiculous argument. The entire point of the post was, as the author even noted, purely to deep dive into a rabbit hole, get super picky & pedantic about standards wording so that you can act surprised that copy constructors exist in C++ while it was completely glossed over in the identical C example of a struct copy initialization, and almost none of this is useful to know. So don't fucking teach it and you'd have plenty of time to cover all that other stuff. Bam, problem solved. Ignore pre-C++11 entirely, and purely teach & use the new stuff which fixes all the complexity, and leave the rabbit hole for people that care about exploring the past. Oh, and don't use standards wording because those are for compilers to use to implement the language, not for programmers to understand how to use it effectively. The only time it's ever useful to know the full definition of an aggregate type or how it has changed is when you want to write a blog post calling them crazy or complex. It's never useful to know when using the language. And if you have an object that cares to enforce it just static_assert(std::is_aggregate_v<A>, "A isn't an aggregate type"); Tada, now the compiler will tell you if/when you violated the rule and you don't need to try and understand the full scope of the ruleset.
- userbinator 8y agouse the new stuff which fixes all the complexity It doesn't, unfortunately it just adds to the complexity.
- throwawaymath 8y agoHow so? My experience has been that it actually reduces net complexity, except in the case where you need to support different versions of the language in the same codebase. Take for example, `auto`, added in C++11. If you don't have to support C++98 or C++03, the use of `auto` significantly simplifies many workflows and is often strictly better with less mental overhead.
- 8y ago
- amelius 8y agoNavigation on this page is also pretty bonkers, iyam.
- lordnacho 8y agoOne thing that's related to syntax and initialization has annoyed me and many other c++ coders for a while: https://en.wikipedia.org/wiki/Most_vexing_parse https://en.wikipedia.org/wiki/Most_vexing_parse And it's one of the motivations for the {} syntax.
- linuxlizard 8y agoC++ is a little like the English language: a bunch of different pieces gathered together over a period of time, new features added to replace/fix old. I like it. (My comment copy/paste from another C++ thread.)
- MikeLui 8y agoAuthor here--some extra context to add: The post was mostly written to point my students to, so I don't have to keep repeating myself. I get a not-insignificant number of 1st, 2nd, and 3rd years (in a 5-year program) believing C is some antiquated language and believing that they're getting held back in some way by learning C vs C++. One even suggested the department was incompetent for not teaching C++. Because I work in an engineering department, many students have not had a great deal of time learning programming fundamentals early on and regardless, they are eager to learn more advanced tools than they are ready to use. It is a bit rambling for the purpose--I have a tendency to...erm, overwhelm...with information to make my point. I haven't blogged much so I originally submitted it at lobste.rs[1] for any advice on the writing and visual style of the site. I welcome any constructive feedback. E.g. "I hate that side-nav! It keeps popping in and out!" Also to clarify, I am not anti-C++ is anyway. I am a firm practitioner of Chesterton's fence[2] and believe in nuance. That cuts both ways. C++ is the way it is because it filled a specific need. It's greatest flaw is trying to appease everyone and, recently, trying to catch up quickly to recent QoL features in other languages. This fortunately gives it a lot of features other languages don't have, and it unfortunately gives it a lot of features other languages don't have. Once again, the greater point being a warning, that C++ can easily become a time sink in language-specific knowledge instead of domain-specific knowledge. Of course sometimes that's what you want, e.g. when trying to optimize for performance. [1]: https://lobste.rs/s/tul188/initialization_c_is_seriously_bonkers https://lobste.rs/s/tul188/initialization_c_is_seriously_bon... [2]: https://en.wikipedia.org/wiki/Wikipedia:Chesterton%27s_fence https://en.wikipedia.org/wiki/Wikipedia:Chesterton%27s_fence
- gamma-male 8y agoWhy not teach rust?
- MikeLui 8y agoI can think of at least 3 reasons! 1) I don’t control the curriculum. 2) I’m pretty sure no one knows it well enough to teach. 3) Rust’s ecosystem and adoption is still too small for being taught as an engineering tool and for delivering employment opportunities to students. I personally like rust and hope it does well. I see it somewhat orthogonal to both C and C++
- jokoon 8y agoHow many languages give you that much precise control over memory? So few.
- mlthoughts2018 8y agoIt reminds me of this gem: https://mobile.twitter.com/timur_audio/status/1004017362381795329 https://mobile.twitter.com/timur_audio/status/10040173623817...
- deleted 8y ago[deleted]