ערוך

שתף באמצעות


Warning C26822

Dereferencing a null pointer 'variable' (lifetime.1)

Remarks

Dereferencing a null pointer is frequent problem in C and C++. We have several checks to deal with such problems. See this blog post for a comparison. When the analysis engine deduces the value of a pointer to be null and sees that pointer get dereferenced, it will emit a C26822 warning. You can also enable C26823 for a stricter analysis. This check also supports SAL annotations and gsl::not_null to describe invariants of the code.

Example

void f(int *p) { 
    if (p == nullptr) 
        *p = 42; // warning: C26822
} 

void assign_to_gsl_notnull() { 
    int* p = nullptr; 
    auto q = gsl::make_not_null(p); // C26822 warning 
} 

To solve this warning, make sure there's no null pointer dereference in the code, potentially by adding null checks. In case the code was found to be correct, false positive findings can often be fixed by using gsl::not_null or SAL annotations. There are some examples how to use some of those annotations below:

_Notnull_ int *get_my_ptr(); 
gsl::not_null<int *> get_my_ptr2(); 

void local_analysis(int *p) { 
    _Analysis_assume_(p != nullptr); 
    *p = 42; 
} 

void local_analysis2(_In_ int *p) { 
    int a = *p; 
}