Skip to content

Commit b199be6

Browse files
committed
Describe nullability heuristics
1 parent ec636c3 commit b199be6

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

docs/code-quality/c6011.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,28 @@ void f([Pre(Null=Yes)] char* pc)
6464
6565
The careless use of `malloc` and `free` leads to memory leaks and exceptions. To minimize these kinds of leaks and exception problems altogether, avoid allocating raw memory yourself. Instead, use the mechanisms provided by the C++ Standard Library (STL). These include [`shared_ptr`](../standard-library/shared-ptr-class.md), [`unique_ptr`](../standard-library/unique-ptr-class.md), and [`vector`](../standard-library/vector.md). For more information, see [Smart Pointers](../cpp/smart-pointers-modern-cpp.md) and [C++ Standard Library](../standard-library/cpp-standard-library-reference.md).
6666
67+
## Heuristics
68+
69+
Pointers are assumed to be non-null unless there is some evidence that they might be null.
70+
In the examples we've seen so far, pointers returned by `malloc` or `new` might be null because allocation might fail.
71+
Another characteristic that the analysis engine uses as evidence of nullability is if the program explicitly checks for null.
72+
This is illustrated in the following examples:
73+
74+
```cpp
75+
void f(int* n)
76+
{
77+
*n = 1; // Does not warn, n is assumed to be non-null
78+
}
79+
80+
void f(int* n)
81+
{
82+
if (n) {
83+
(*n)++;
84+
}
85+
*n = 1; // Warns because the earlier conditional shows that n might be null
86+
}
87+
```
88+
6789
## See also
6890

6991
- [Using SAL Annotations to reduce code defects](using-sal-annotations-to-reduce-c-cpp-code-defects.md)

0 commit comments

Comments
 (0)