csharp / expert
Snippet
Zero-Allocation Buffers with Stackalloc
For performance-critical and security-sensitive tasks, stackalloc provides memory that is automatically reclaimed when the method returns. Using it with Span<T> provides a safe wrapper that prevents typical buffer overflow vulnerabilities associated with raw pointers.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public unsafe void HashSecret(ReadOnlySpan<byte> data){// Allocates 64 bytes on the stack, bypassing the GC heap entirelySpan<byte> buffer = stackalloc byte[64];if (data.Length > buffer.Length)throw new ArgumentException("Data too large");data.CopyTo(buffer);// Security: Clear the sensitive data from the stack before returningbuffer.Clear();}
Breakdown
1
stackalloc byte[64]
Allocates memory directly on the execution stack of the current thread.
2
buffer.Clear()
Overwrites the memory with zeros to ensure sensitive data doesn't persist in RAM.