Stackalloc inside a loop
23
24 // CS-W1025: Potential memory leak inside `for` loop due to `stackalloc`.
25 // https://deepsource.io/directory/analyzers/csharp/issues/CS-W1025.
26 for ( /* some condition */;;)27 {28 var buffer = stackalloc byte[16];29 }30 }
31}
Description
A stackalloc
expression allocates a block of memory on the stack and is cleaned up only when the controller exits the method. Placing a stackalloc
expression inside a loop continuously allocates memory and does not let it get discarded despite the controller exiting the loop's scope. It is therefore recommended that you rethink your approach.