Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are arrays in .NET naturally aligned?

Tags:

.net

clr

Does .NET make any guarantees that .NET byte arrays are always properly aligned? I do need this to treat e.g. a byte array in unsafe context as longs in x64 to modify chunks of data with the native register size.

But so far I have not found any documentation that the CLR does give me any guarantees that my memory access is then properly aligned.

like image 338
Alois Kraus Avatar asked Mar 19 '13 14:03

Alois Kraus


1 Answers

No. And in fact arrays can be mis-aligned for the x86 jitter. Particularly a problem with double[] and long[], the garbage collector only provides a guarantee that they will be aligned at 4. Which explains the special rule for double[], such an array will be allocated in the Large Object Heap when it has 1000 or more elements. Considerably less than the normal rule for LOH allocations, 85000 or more bytes. The LOH depends on Windows heap alignment guarantees, aligned at 8. This is not otherwise a problem in the x64 jitter.

Getting a bit more specific to your question: byte arrays can never be a problem. A byte is always aligned, no matter where the array starts. A "long" in unmanaged code compiled with the Microsoft compiler is not a problem either, it is 4 bytes so always aligns happily with the default GC alignment rules. It is still 4 bytes in x64 mode so no problem there either.

like image 162
Hans Passant Avatar answered Sep 18 '22 10:09

Hans Passant