When to use _Notnull_ in C++?

1k views Asked by At

Can someone provide insight when to use _Notnull_? I'm using Visual Studio 2019 and here is my code:

#include <windows.h>
#include <vector>
void WriteIt(_Notnull_ CONST WCHAR* sMsg, _Notnull_ CONST WCHAR* sFileName)
{
    FILE* stream;
    errno_t err = _wfopen_s(&stream, sFileName, L"a+");
    if (err == 0)
        if (stream)
            {
            fwprintf_s(stream, L"%s", sMsg);
            fclose(stream);
            }
}
int main()
{
    WCHAR *sMessage = new WCHAR[16]();
    WCHAR *sFile = NULL;
    sFile = NULL;
    WriteIt(sMessage, sFile);
}

Yet, the _Notnull_ lets the function run. I can't find any documentation on how/why to use it with examples.

1

There are 1 answers

0
JeffR On

Thanks @François Andrieux. Looks like it is used when doing a code analysis from within Visual Studio, where the analyzer can pinpoint if an incoming pointer could be NULL. Here is what the code analyzer says with _Notnull_ is included: Warning C6387 'sFile' could be '0': this does not adhere to the specification for the function 'WriteIt'. Very helpful!