Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> C programmers, then `int x;` can either have a value which is just not known at compile time

I am pretty sure that in C, when a program reads uninitialized variable, it is an "undefined behavior", and it is pretty much allowed to be expected to crash — for example, if the variable turned out to be on an unallocated page of stack memory.

So literally the variable does not have a value at all, as that part of address space is not mapped to physical memory.



The problem is that “allowed to be expected to crash” is one interpretation. Another is “0 initialized” (which debug runtimes sometimes use), another is “whatever was on the stack last time” and another is “we can reorder program and eliminate what you think is logical code”.

    int main() {
      int val;
      if (val == 3) {
        cout << “here” << end;
      }
      return 0;
    }
A perfectly legal interpretation of this program is to remove the call to cout, as is just printing “here” on every run.

> So literally the variable does not have a value at all, as that part of address space is not mapped to physical memory.

There are vanishingly few platforms where the stack you have in a C program maps to physical memory (even if you consider pages from the OS)


It is "undefined behaviour" in C (which is an overloaded term which I will not discuss why I hate it in this comment). But my point was that is how many people conceptualize it, and for many things people do expect it to be one of the possible values, just not knowable ahead of time.

However, I was using that "C programmers" bit to explain the conceptualization aspect, and how it also applies to other languages. Not every language, even systems languages, have the same concepts as C, especially the same construction as "UB".


It is undefined in C for automatic variables whose address was not taken (and in this case a compiler should be able to warn).


As someone who recently wondered what kinds of things might happen, im actually very glad for GPs clarification.


Interestingly enough, C++26 introduces "erroneous behavior" and uses it for uninitialized variables, rather than undefined behavior.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: