Do you still need to zero-initialize stackalloc using Span<T>.Clear()? #74860
-
From this blog post back in 2020:
The stackalloc documentation also says:
However, I haven't come across a case where it hasn't been zero-initialized, and I thought that example (Debug vs Release) was fixed. Is this still necessary in .NET 6 and the upcoming 7? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
As you've read, the only guarantee you get is that there is no guarantee. You don't necessarily need to use In practice though, locals (including stack allocations) will always be initialized to zero unless you use However if you're relying on this, you're still relying on unspecified behavior. You're also creating a ticking time bomb if anyone were to apply If you do want to rely on the stackalloc being initialized to zero and you don't want to pay the cost of double-initializing it: You should explicitly clear it and apply |
Beta Was this translation helpful? Give feedback.
As you've read, the only guarantee you get is that there is no guarantee. You don't necessarily need to use
Span.Clear
, but you need to ensure you don't read data which wasn't previously written.In practice though, locals (including stack allocations) will always be initialized to zero unless you use
SkipLocalsInit
, which is why you aren't ever seeing it as non-zero. (I don't think it has ever actually differed between debug and release builds.)However if you're relying on this, you're still relying on unspecified behavior. You're also creating a ticking time bomb if anyone were to apply
SkipLocalsInit
project-wide. (Which is not uncommon in performance-minded code bases.)If you do wa…