| 屬性 | 值 |
|---|---|
| 規則識別碼 | CA2014 |
| 職稱 | 請勿在迴圈中使用 stackalloc |
| 類別 | 可靠性 |
| 修正程式是中斷或非中斷 | 不中斷 |
| 在 .NET 10 中預設啟用 | 作為警告 |
原因
在迴圈內使用 C# stackalloc 運算式 。
檔案描述
C# stackalloc 表達式會從目前的堆疊框架配置記憶體,而且在目前方法呼叫傳回之前,可能不會釋放該記憶體。 如果在 stackalloc 迴圈中使用 ,可能會導致堆疊溢出,因為堆疊記憶體耗盡。
如何修正違規
將 stackalloc 表達式移至 方法中所有迴圈之外。
Example
// This method violates the rule.
public void ProcessDataBad()
{
for (int i = 0; i < 100; i++)
{
// CA2014: Potential stack overflow.
// Move the stackalloc out of the loop.
Span<int> buffer = stackalloc int[100];
buffer[0] = i;
// ...
}
}
// This method satisfies the rule.
public void ProcessDataGood()
{
Span<int> buffer = stackalloc int[100];
for (int i = 0; i < 100; i++)
{
buffer[0] = i;
// ...
}
}
隱藏警告的時機
當只叫用包含迴圈或迴圈時,隱藏警告可能很安全,因此已知所有 stackalloc 作業配置的總記憶體數量相對較小。
隱藏警告
如果您只想要隱藏單一違規,請將預處理器指示詞新增至原始程式檔以停用,然後重新啟用規則。
#pragma warning disable CA2014
// The code that's violating the rule is on this line.
#pragma warning restore CA2014
[*.{cs,vb}]
dotnet_diagnostic.CA2014.severity = none
若要停用此整個規則類別,請將組態檔中類別的嚴重性設定為 none。
[*.{cs,vb}]
dotnet_analyzer_diagnostic.category-Reliability.severity = none
如需詳細資訊,請參閱 如何隱藏程式代碼分析警告。