You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/standard/unsafe-code/best-practices.md
+6Lines changed: 6 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -669,6 +669,7 @@ the intended logic.
669
669
### Recommendations
670
670
671
671
1. ✔️ DO always consume `stackalloc` into `ReadOnlySpan<T>`/`Span<T>` on the left side of the expression to provide bounds checks:
672
+
672
673
```cs
673
674
// Good:
674
675
Span<int>s=stackallocint[10];
@@ -680,9 +681,11 @@ the intended logic.
680
681
s[2] =0;
681
682
s[42] =0; // Out of bounds write, undefined behavior.
682
683
```
684
+
683
685
2. ❌ DON'T use `stackalloc` inside loops. The stack space isn'treclaimeduntilthemethodreturns, soincludinga `stackalloc` insidealoopcouldresultinprocessterminationduetostackoverflow.
684
686
3. ❌ DON'T use large lengths for `stackalloc`. For example, 1024 bytes could be considered a reasonable upper bound.
@@ -775,6 +779,7 @@ can lead to information disclosure, data corruption, or process termination via
775
779
1. ❌ DON'T expose methods whose arguments are pointer types (unmanaged pointers `T*` or managed pointers `ref T`) when those arguments are intended to represent buffers. Use safe buffer types like `Span<T>` or `ReadOnlySpan<T>` instead.
776
780
2. ❌ DON'T use implicit contracts for byref arguments, such as requiring all callers to allocate the input on the stack. If such a contract is necessary, consider using [ref struct](https://learn.microsoft.com/dotnet/csharp/language-reference/builtin-types/ref-struct) instead.
777
781
3. ❌ DON'T assume buffers are zero-terminated unless the scenario explicitly documents that this is a valid assumption. For example, even though .NET guarantees that `string` instances are null-terminated, the same does not hold of other buffer types like `ReadOnlySpan<char>` or `char[]`.
@@ -803,6 +808,7 @@ can lead to information disclosure, data corruption, or process termination via
803
808
}
804
809
}
805
810
```
811
+
806
812
4. ❌ DON'T pass a pinned `Span<char>` or `ReadOnlySpan<char>` across a p/invoke boundary unless you have also passed an explicit length argument. Otherwise, the code on the other side of the p/invoke boundary might improperly believe the buffer is null-terminated.
0 commit comments