11 ms·
> In Odin all variables are automatically zero initialized. Not just integers and floats. But all structs as well. Their memory is filled with zeroes when those
by mrkeen 1y ago
> In Odin all variables are automatically zero initialized. Not just integers and floats. But all structs as well. Their memory is filled with zeroes when those variables are created.
> This makes ZII extra powerful! There is little risk of variables accidentally being uninitialized.
The cure is worse than the problem. I don't want to 'safely' propagate my incorrect value throughout the program.
If we're in the business of making new languages, why not compile-time error for reading memory that hasn't been written? Even a runtime crash would be preferable.
- ratatoskrt 1y ago> why not compile-time error for reading memory that hasn't been written? so... like Rust?
- Timwi 1y agoCuriously, C# does both. It uses compile-time checks to stop you from accessing an uninitialized local and from exiting a struct constructor without initializing all fields; and yet, the CLR (the VM C# compiles to) zero-initializes everything anyway.
- dontlaugh 1y agoThat’s likely because p/invoke is quite common.
- neonsunset 1y agoNo, that's just the memory model of CLI and the choice made by C#. By default, it emits localsinit flag for methods which indicates that all local variables must be zero-initialized first. On top of that, you can't really access unitialized memory in C# and F# anyway unless you use unsafe. It's a memory safety choice indeed but it has nothing to do with P/Invoke.
- dontlaugh 1y agoThe main motivation to use unsafe is p/invoke. Without unsafe, zero init is not needed.
- neonsunset 1y ago> The main motivation to use unsafe is p/invoke. This is opposite to the way unsafe (either syntax or known unsafe APIs) is used today.
- dontlaugh 1y agoExplicit use of unsafe is used for things like avoiding allocation, sure. All use of p/invoke is also unsafe though, even if the keyword isn’t used. And it’s much more common to wrap a C library than to write a buffer pool.
- mrkeen 1y agoThis is a pain. I recently switched from Java (and its whole Optional/null mess) to C#. I was initially impressed by its nullable checks, but then I discovered 'default'. Now I gotta check that Guids aren't 0000...? It makes me miss the Java situation.
- electroly 1y agoYou don't need the "default" keyword to run into that. A simple "new Guid()" gives you all-zeroes (try it!). Nice and foot-gunny.
- masfoobar 1y ago> A simple "new Guid()" gives you all-zeroes In C#, to have all zeroes, you would do "Guid.Empty"
- masfoobar 1y ago(continued from my comment above) Apologies, I am missing some text on here. No sure what happened. I might have deleted before I submitted. I cannot edit this comment, but I need to clarify and correct it... "new Guid()" is equiverlant "Guid.Empty" Personally, I would prefer writing "Guid.Empty" as it is cleaner. It also helps ensure you understand reading other developers code... their intensions. Afterall, a lesser experienced developer may not know (or simply forgot) that "new Guid()" does not create a new, unique value. So writing "new Guid()" looks more misleading. var myGuid1 = new Guid(); // all zeroes, or a value? var myGuid2 = Guid.Empty; // Ah.. all zeroes. It is ESPECIALLY cleaner when doing comparison :- if(myGuid2 == Guid.Empty) { } To set a Guid, you would do :- myGuid2 = Guid.NewGuid(); // This makes sense.
- neonsunset 1y agoOnly if you go out of your way to author a method with (Guid someGuid = default) argument. I've never seen it happen with Guids, if someone gives you default(Guid) - they did it on purpose, it's no different to explicitly setting `0` to an integer-typed UserID property. If supplying Guid is optional, you just make it Guid?. To be fair, I don't think offering default(T) by default (ha) is the best choice for structs. In F#, you have to explicitly do `Unchecked.defaultOf` and otherwise it will just not let you have your way - it is watertight. I much prefer this approach even if it can be less convenient at times.
- deleted 1y ago[deleted]
- munificent 1y agoIt has to because the analysis to detect that fields are initialized in the constructor body is unsound. Since you have access to `this` inside the constructor, you can call other instance methods which may access fields before they have been initialized. Java has the same problem. (Dart, which I work on, does not. In Dart, you really truly can't observe an instance field before it has been initialized.)
- thasso 1y agoI agree that zero-initializing doesn't really help avoid incorrect values (which is what the author focuses on) but at least you don't have UB. This is the main selling point IMO.
- yusina 1y agoThen why not just require explicit initialization? If "performance" is your answer then adding extra optimization capabilities to the compiler that detects 0 init would be a solution which could skip any writes if the allocator guarantees 0 initialization of allocated memory. A much safer alternative. Replacing one implicit behavior with another is hardly a huge success...
- 90s_dev 1y agoI'd guess it was because 0 init is desired often enough that this is a convenient implicit default?
- yusina 1y ago"Often enough" is what's introducing the risk for bugs here. I "often enough" drive around with my car without crashing. But for the rare case that I might, I'm wearing a seatbelt and have an airbag. Instead of saying "well I better be careful" or running a static analyzer on my trip planning that guarantees I won't crash. We do that when lives are on the line, why not apply those lessons to other areas where people have been making the same mistakes for decades?
- johnnyjeans 1y agoFor the same reason you wear a seatbelt and not a 7-point crash harness.
- sph 1y agoPlease, can we stop assuming every single software has actual lives on the line? These comment threads always devolve into implicit advertisement of Rust/Ada and other super strict languages because “what about safety?!” It is impossible to post about a language on this forum before the pearl clutching starts if the compiler is a bit lenient instead of triple checking every single expression and making your sign a release of liability. Sometimes, ergonomics and ease-of-programming win over extreme safety. You’ll find that billion dollar businesses have been built on zero-as-default (like in Go) and often people reaching for it or Go are just writing small personal apps, not cruise missile navigation system. It gets really tiring. /rant
- tlb 1y agoBeing initialized to zero is at least repeatable, so if you forget to initialize something you'll notice it immediately in testing. The worst part about uninitialized variables is that they frequently are zero and things seem to work until you change something else that previously happened to use the same memory.
- thasso 1y ago> The worst part about uninitialized variables is that they frequently are zero and things seem to work until you change something else that previously happened to use the same memory. This is not the whole story. You're making it sound like uninitialized variables _have_ a value but you can't be sure which one. This is not the case. Uninitialized variables don't have a value at all! [1] has a good example that shows how the intuition of "has a value but we don't know which" is wrong: use std::mem; fn always_returns_true(x: u8) -> bool { x < 120 || x == 120 || x > 120 } fn main() { let x: u8 = unsafe { mem::MaybeUninit::uninit().assume_init() }; assert!(always_returns_true(x)); } If you assume an uninitialized variable has a value (but you don't know which) this program should run to completion without issue. But this is not the case. From the compiler's point of view, x doesn't have a value at all and so it may choose to unconditionally return false. This is weird but it's the way things are. It's a Rust example but the same can happen in C/C++. In [2], the compiler turned a sanitization routine in Chromium into a no-op because they had accidentally introduced UB. [1]: https://www.ralfj.de/blog/2019/07/14/uninit.html https://www.ralfj.de/blog/2019/07/14/uninit.html [2]: https://issuetracker.google.com/issues/42402087?pli=1 https://issuetracker.google.com/issues/42402087?pli=1
- gingerBill 1y ago> You're making it sound like uninitialized variables _have_ a value but you can't be sure which one. Because that's a valid conceptualization you could have for a specific language. Your approach and the other person's approach are both valid but different, and as I said in another comment, they come with different compromises. If you are thinking like some C programmers, then `int x;` can either have a value which is just not known at compile time, or you can think of it having a specialized value of "undefined". The compiler could work with either definition, it just happens that most compilers nowadays do for C and Rust at least use the definition you speak of, for better or for worse.
- gingerBill 1y agoYou're assuming that's the style of programming others want to program in. Some people want the "ZII" approach. Your approach is a trade-off with costs which many others would not want to make. So it's not "preferable", it's a different compromise.
- iainmerrick 1y agoThat's clearly correct, as e.g. Go uses this style and there are lots of happy Go users. I want to push back on the idea that it's a "trade-off", though -- what are the actual advantages of the ZII approach? If it's just more convenient because you don't have to initialize everything manually, you can get that with the strict approach too, as it's easy to opt-in to the ZII style by giving your types default initializers. But importantly, the strict approach will catch cases where there isn't a sensible default and force you to fix them. Is it runtime efficiency? It seems to me (but maybe not to everyone) that initialization time is unlikely to be significant, and if you make the ZII style opt-in, you can still get efficiency savings when you really need them. The explicit initialization approach seems strictly better to me.
- gingerBill 1y ago> It seems to me... that initialization time is unlikely to be significant The thing is, initialization cost is a lot more than you think it is, especially when it's done on a per-object level rather than a "group" level. This is kind of the point of trying to make the zero value useful, it's trivially initialized. And in languages that are much more strict in their approach, it is done at that per-object level which means instead of the cost of initialization being anywhere from free (VirtualAlloc/mmap has to produce zeroed memory) to trivially-linear (e.g. memset), to being a lot more nested hierarchies of initialization (e.g. for-loop with constructor for each value). It's non-obvious why the "strict approach" would be worse, but it's more about how people actually program rather than a hypothetical approach to things. So of course each style is about trade-offs. There are no solutions, only trade-offs. And different styles will have different trade-offs, even if they are not immediately obvious and require a bit of experience. A good little video on this is from Casey Muratori, "Smart-Pointers, RAII, ZII? Becoming an N+2 programmer": https://www.youtube.com/watch?v=xt1KNDmOYqA https://www.youtube.com/watch?v=xt1KNDmOYqA
- slowmovintarget 1y agoHere's Casey Muratori on his habit of moving to ZII: https://www.youtube.com/watch?v=xt1KNDmOYqA https://www.youtube.com/watch?v=xt1KNDmOYqA Much better outcomes and failure modes than RAII. IIRC, Odin mentions game programming as one of its use cases.
- CyberDildonics 1y agoThese are not very good arguments and Casey Muratori is hugely biased against RAII and C++ techniques for some reason, probably familiarity with C. He thinks that every RAII variable is a failure point and that you only have to think about ownership if you are using RAII, so it incurs mental overhead. The reality is that you have to understand the lifetime and ownership of your allocations no matter what. If the language does nothing for you the allocation will still have a lifetime and a place where the memory is deallocated. He also talks about combining multiple allocations in to a single allocation that then gets split into multiple pointers, but that could easily be done in C++.
- adamrezich 1y ago> He also talks about combining multiple allocations in to a single allocation that then gets split into multiple pointers, but that could easily be done in C++. But this is explicitly the opposite of how the language is designed to be used, because that's the whole point of RAII.
- CyberDildonics 1y agoBut this is explicitly the opposite of how the language is designed to be used, because that's the whole point of RAII. Says who? If they all have the same lifetime multiple allocations can be combined into one allocation and deallocation. I've done it before, it makes perfect sense, although I would say it is a somewhat niche optimization.
- adamrezich 1y agoIt's only a “somewhat niche optimization” because the language emphasizes RAII. There are other ways of writing code—which other languages can incentivize by being designed differently—where it is not a niche optimization, but rather the default.
- lerno 1y agoI always find this opinion intriguing, where it's apparently fine that globals are initialized to zero, but you are INSANE to suggest it's the default for locals. What kind of programs are y'all writing? Clearly the lack of zeroing in C was a trade-off at the time. Just like UB on signed overflow. And now people seem to consider them "obvious correct designs".
- Tuna-Fish 1y agoI'd prefer proper analysis for globals too, but that is substantially harder. "Improperly using a variable before it is initialized" is a very common class of bug, and an easy programming error to make. Zero-initializing everything does not solve it! It just converts the bugs from ones where random stack frame trash is used in lieu of the proper value into ones where zeroes are used. If you wanted a zero value, it's fine, but quite possibly you wanted something else instead and missed it because of complex initialization logic or something. What I want is a compiler that slaps me when I forget to initialize a proper value, not one that quietly picks a magic value it thinks I might have meant.
- nickpsecurity 1y agoIt might be easier to detect a zero value. It might be easier to debug. People used to use hard-coded, human-visible values for debugging for that reason.
- Tuna-Fish 1y agoSure, and I'm not against belt-and-suspenders here. It's just that "all values are defined to be zero-initialized, and you can use them as such" is a horrible decision. It means that you cannot even get best effort warnings for lack of initialization, because as far as the compiler knows you might have meant to use the zero value.
- fc417fc802 1y agoI suspect it's even worse than UB. At least in that case a sanitizer can prevent optimizations and detect the later usage. If default zero initialization is guaranteed then as you say you lose any chance of an automated system detecting the programmer error.
- dooglius 1y ago> why not compile-time error for reading memory that hasn't been written https://en.wikipedia.org/wiki/Rice%27s_theorem?useskin=vector https://en.wikipedia.org/wiki/Rice%27s_theorem?useskin=vecto...
- TheCoelacanth 1y agoA compiler doesn't have to accept all possible programs. If it can't prove that a variable is initialized before being read, then it can simply require that you explicitly initialize it.
- dooglius 1y agoSure, but then not accepting many programs would be the answer to parent's question "why not"
- jerf 1y agoNot accepting many C programs, maybe. It's pretty easy to create a language where declaration is initialization of some sort, as evidenced by the large number of languages in common use where, one way or another, that's already the case. This isn't some whacko far out idea. Most languages already today don't have any way (modulo "unsafe", or some super-carefully declared and defined method that is not the normal operation of the language) of reading uninitialized memory. It's only the residual C-likes bringing up the rear where this is even a question. (I wouldn't count Odin's "explicitly label this as not getting initialized"; I'm talking about defaults being sharp and pointy. If a programmer explicitly asks for the sharp and pointy, then it's a valid choice to give it to them.)
- dooglius 1y agoI think we are in agreement? Odin works the way you describe, and GP in response expressed a preference that the compiler instead fail at compile time if it detected that memory had not been explicitly initialized; my response was to explain why this is not (in the general case) feasible.
- drannex 1y agoNot sure if anyone has mentioned it, but you can additionally disable ZII in any variable by describing the value as "---" in your declaration, useful when writing high performance code, here is an example: number: int = ---
- lblume 1y agoYes, this is mentioned explicitly in the article.
- melodyogonna 1y agoYou're talking about Mojo there. Even memory allocated with UnsafePointer must be explicitly initialised before it can be written to or read from.
- variadix 1y agoThis is certainly an interesting argument for making certain behavior (in this case, uninitialized access) the default and UB. There’s a similar argument for making signed overflow UB instead of defined to wrap, even if you’re only targeting two’s-complement machines, that is: leaving the behavior undefined enables analyzers to detect the behavior and making it the default can make otherwise silent errors detectable across all programs. I think I’ve come around to wanting these to be undefined and the default, it’s unintuitive but defined wrapping or zero initialized may be undesirable behaviors anyway.
- jimbob45 1y agoThe dangerous behavior should be opt-in, not opt-out. I appreciate that C gives you all of these neat footguns but they need to be hidden to find for only those who need them. Stuff like implicitness being the default for functions, int wrapping, and non-initialized variables just give rise to bugs. And for what? So first-year students can have their unoptimized code be 0.00001% faster by default? It's dumb.
- variadix 1y agoIf it’s opt-in then code written for the default (ie most code that wasn’t written to use the unintuitive behavior for some performance reason) will be either well-formed code that relies on the behavior (fine, but for signed int wrapping this is rare, for zero init this is common but not always the case) or ill-formed code that subtly fails (e.g. no check for overflow or zero is an invalid value). The code that is ill-formed cannot be checked by present or future static or dynamic analyzers, since the failure condition (signed overflow or access before assignment) is _defined to be something valid_ thereby preventing analyzers from determining whether the programmer intended the signed arithmetic to overflow or not, or for that value to be zero or not, etc. Hopefully I’m communicating why it is useful to leave the default behavior undefined or invalid. It doesn’t really have to have anything to do with performance, signed wrapping is no less performant on two’s-complement machines (barring compiler optimizations enabled by assuming no overflow) since it is the result produced by add instructions on overflow. The benefit is that it enables instrumentation and analyzers to detect this behavior because it is known to be invalid and not something the programmer intended. As an analogy, consider what would happen if you defined out of bounds array access to be _something_, now analyzers and instrumentation cannot detect this as an error, since the programmer may have intended for whatever that defined result is to occur in that case.
- canucker2016 1y agoSo fixing approx. 5-10% of CVEs (by zero-initializing all stack vars) is a worse cure than letting these uninitialized stack vars be possible sources of exploits? see https://msrc.microsoft.com/blog/2020/05/solving-uninitialized-stack-memory-on-windows/ https://msrc.microsoft.com/blog/2020/05/solving-uninitialize... Initializing the stack var to zero would have helped mitigate the recently discovered problem in GTA San Andreas (the real problem is an unvalidated data file) - see https://cookieplmonster.github.io/2025/04/23/gta-san-andreas-win11-24h2-bug/ https://cookieplmonster.github.io/2025/04/23/gta-san-andreas...
- Arnavion 1y ago>So fixing approx. 5-10% of CVEs (by zero-initializing all stack vars) is a worse cure than letting these uninitialized stack vars be possible sources of exploits? Read the comment you responded to again, carefully. It's not presenting the dichotomy you think it is.
- the__alchemist 1y agoSame. Rust's `Default` (Both derive, and custom) is my favorite way of handling a quick init, of any language. The key part is I can initialize quickly and without effort, with values that make sense based on the context.