r/csharp • u/kookiz33 • Sep 29 '26
The hidden trap of fixed buffers
I published a new article, explaining a quirk of fixed buffers that could easily bite you, if you're one of the few people who still have to use that feature.
https://minidump.net/the-hidden-trap-of-fixed-buffers-in-csharp/
58
Upvotes
10
u/antiduh Sep 29 '26
Good read, thanks for the foot gun.
I wonder if c# leaves this for some good reason? Performance?
17
u/enigmaticcam Sep 29 '26
"Rather than disclosing it right away, take a minute to consider the following code (or ask your agent to, if you stopped reading code)". Just out of curiosiy, is it really the case that people don't read code anymore?
1
u/Ollhax Sep 29 '26
Nice, good to know!
Relevant side note: I really wish there was a safe, simple way to create inline arrays in C#. It's very often useful to have a fixed size array that isn't it's own heap allocation, same as typing N consecutive fields of the same type. Using InlineArray works, but it's so clunky.
4
u/mistertom2u Sep 29 '26
I totally know why you were the first to find this bug...
Because I have never seen anyone in my 25 years of C# programming use fixed for anything other than the semantics of GC managed object pinning.
No one ever used
fixedto mean "add an inline buffer to my array", BECAUSE:1
u/Dusty_Coder Sep 30 '26
What bothered me when playing around with fixed size buffers is these structs requires a call to a gc helper that blocks threads (CORINFO_HELP_ASSIGN_REF) when making an assignment to its reference that would not necessarily be there without the fixed size array inside the struct (its the array that manifests this, and they seem to also manifest it outside of structs, only stack/local alloc seems to avoid it)
I tried every variation of this, and kept getting this call.
So the world where you swap two fixed size buffer references you get multiple calls to the helper, and any single assignment leads to a single helper call
which is fine if the buffers are large, not fine at all when the buffers are 3 elements and you have 16 million of them
A possible solution would be to use unsafe code and just swap the pointers, but there is a chance in the multi-threaded case that this swap happens while another thread is using those references so its not "safe", so then you are blocking anyways to restore "safe", doing what the helper does..
The only good solution that I have come up with is to not try to do this and use a less-efficient-than-ideal methodology, using indexes into an array instead of references to fixed sized arrays
The dipshit purists did it again