Visual Studio "Dereferencing Null Pointer" Warning

Visual Studio "Dereferencing Null Pointer" Warning

I have a function that creates an address, stores values at the address contiguously, and then returns the address:

double* quadratic(double a, double b, double c)
{
    double* solAddr = malloc((size_t)(2 * sizeof(double)));

    *(solAddr) = (-b + sqrt(b * b - 4.0 * a * c)) / 2.0 * a;
    *(solAddr + 1) = (-b - sqrt(b * b - 4.0 * a * c)) / 2.0 * a;

    return solAddr;
}

However, I'm getting a warning that states Warning C6011 Dereferencing NULL pointer 'solAddr'. After some online searching, I found that I simply need to make sure solAddr is not NULL with an "if"- statement and the warning disappears:

double* quadratic(double a, double b, double c)
{
    double* solAddr = malloc((size_t)(2 * sizeof(double)));

    if (solAddr != NULL)
    {
        *(solAddr) = (-b + sqrt(b * b - 4.0 * a * c)) / 2.0 * a;
        *(solAddr + 1) = (-b - sqrt(b * b - 4.0 * a * c)) / 2.0 * a;
    }

    return solAddr;
}

Does the warning really mean that solAddr may be NULL? It seems that the text states otherwise. The code works both with and without the NULL check but I'm confused as to what this warning is really trying to tell me.

3

1 Answer

Yes, that warning is there because malloc could return NULL if allocation failed.

It's actually a warning from SAL annotations applied to the library headers, not Visual Studio itself. You should always check malloc return value for NULL and handle it, because malloc could return NULL if it fails. My usual method is:

   space = malloc(SIZE);
   if(NULL == space)
   {
       goto cleanup;
   }

   use(space);

cleanup:
   free(space);
   space = NULL;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Alexander Ross
Author

Alexander Ross

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.