取消引用变量可能为空¶
ID: cs/dereferenced-value-may-be-null
Kind: path-problem
Security severity:
Severity: warning
Precision: high
Tags:
- reliability
- correctness
- exceptions
- external/cwe/cwe-476
Query suites:
- csharp-security-and-quality.qls
如果取消引用变量(例如,作为方法调用中的限定符),并且在导致取消引用的某些执行路径上,该变量可能具有 null
值,则取消引用可能会导致 NullReferenceException
。
建议¶
确保在取消引用变量时,该变量不具有 null
值。
示例¶
在以下示例中,方法 DoPrint()
无条件地取消引用其参数 o
,从而通过调用 DoPrint(null)
导致 NullReferenceException
。
using System;
class Bad
{
void DoPrint(object o)
{
Console.WriteLine(o.ToString());
}
void M()
{
DoPrint("Hello");
DoPrint(null);
}
}
在修改后的示例中,方法 DoPrint()
使用 null
检查来保护取消引用操作。
using System;
class Good
{
void DoPrint(object o)
{
if (o != null)
Console.WriteLine(o.ToString());
}
void M()
{
DoPrint("Hello");
DoPrint(null);
}
}
参考¶
Microsoft,NullReferenceException 类。
常见弱点枚举:CWE-476。