Hacker News new | past | comments | ask | show | jobs | submit login

>Why can't we wait and let that be the first value that's actually meaningful instead of wasting time writing 0's?

Rust lets you do that.

    let m: u32; // note: no mut
    m = 5;
Even this is totally fine:

    let m: u32; // note: no mut
    if true {
       m = 5
    } else {
       m = 2
    }
>I know rust considers uninitialized memory unsafe but I don't get why

It is wildly unsafe, because the compiler has to be able to rely on the fact that memory slots it emits assembly code for actually use only those bits the compiler knows are in use.

For example, on ARM you have no registers < 32 bit. So the compiler has to use those registers for u8 as well, but it has to be sure that nobody actually sets the high bits, otherwise multiplication (etc) would do completely insane things and not at all what the program should have done.

Similarly, memory slots have a size that is a multiple of 8 bits (because the load/store instructions usually can load/store exactly 8, 16, 32 bits etc) and your type doesn't necessarily have exactly that number of possible inhabitants of the type (it would only be the case if number of possible inhabitants = 2^(8 n) where n is a natural number). Clearly, this is not possible to ensure in general.

Of course you have the compiler be totally defensive about it and issue masking instructions all the time--but that would make the resulting program slow.

Also, think of a bool. It has two possible values, right? But in C, any value that is not equal to 0 is defined to be true.

Now when the compiler emits code for a && b it can't do the obvious which would be

   and r0, r1, r2
because that will do bitwise-and and let's say a = 4 and b = 1 then a bitand b = 0 but what you wanted is a && b == 1 since a is true and b is true. Worse if a = 5 and b = 1, it suddenly works.

So that would be a bad idea as well (you'd have to emit extra instructions to check whether a is 0 and so on).

>Why is it important to initialize memory to 0's before we use it?

It's not. It's just C being C.

I'd actually prefer C to have an alloc function with two arguments m and n where it does m * n with overflow checking and then allocates that and then does NOT initialize the memory to 0's.

That said, todays computers are very fast and 0 has no data dependencies. So I wonder how much overhead, if any, in wall time, it adds to always zero out.




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

Search: