Reputation: 69
byte[] buffer = new byte[500000];
initializes buffer with 0 values. As it is a buffer, I dont want any initialization, is it possible in C# as in C?
Upvotes: 2
Views: 3285
Reputation: 28091
A way in C# to do what malloc
does in C is to use Marshal.AllocHGlobal
in an unsafe
context:
unsafe
{
var ptr = Marshal.AllocHGlobal(50000 * sizeof(int));
int* values = (int*)ptr;
// lists uninitialized ints
for (int i = 0; i < 50000; i++)
Console.WriteLine(values[i]);
Marshal.FreeHGlobal(ptr);
}
Upvotes: 1
Reputation: 6564
Fill it with random numbers or use DllImport
and VirtualAlloc
from Win32 API.
Upvotes: 0
Reputation: 111830
I don't think it is possible... Even FormatterServices.GetUninitializedObject that doesn't run constructors:
Because the new instance of the object is initialized to zero and no constructors are run, the object might not represent a state that is regarded as valid by that object.
Note that if you want unmanaged (memory taken from the OS that isn't GC-managed), that can be allocated without zeroing it, but it wouldn't be a byte[]
.
Upvotes: 1