Skip to content

Commit da09f4e

Browse files
Merge pull request #4918 from eholk/c6011-new-delete
Update C6011 documentation
2 parents 5f325f4 + e7fa61d commit da09f4e

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

docs/code-quality/c6011.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,10 +64,33 @@ 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+
A heuristic used to reduce the number of warnings in legacy code assumes that a pointer is non-`NULL` unless there is evidence that it is `NULL`. In the examples we've seen so far, pointers returned by `malloc` or `new` might be `NULL` because allocation might fail. Another characteristic that the analysis engine uses as evidence of nullability is if the program explicitly checks for `NULL`. This is illustrated in the following examples:
70+
71+
```cpp
72+
void f(int* n)
73+
{
74+
*n = 1; // Does not warn, n is assumed to be non-null
75+
}
76+
77+
void f(int* n)
78+
{
79+
if (n) {
80+
(*n)++;
81+
}
82+
*n = 1; // Warns because the earlier conditional shows that n might be null
83+
}
84+
```
85+
86+
In the second case, the user can fix the warning by moving the `*n = 1` line inside the if block.
87+
6788
## See also
6889

6990
- [Using SAL Annotations to reduce code defects](using-sal-annotations-to-reduce-c-cpp-code-defects.md)
7091
- [`NULL`](../c-runtime-library/null-crt.md)
7192
- [Indirection and Address-of Operators](../c-language/indirection-and-address-of-operators.md)
7293
- [`malloc`](../c-runtime-library/reference/malloc.md)
7394
- [`free`](../c-runtime-library/reference/free.md)
95+
- [`new` operator](../cpp/new-operator-cpp.md)
96+
- [`delete` operator](../cpp/delete-operator-cpp.md)

0 commit comments

Comments
 (0)