cmemorysal

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.


Solution

  • 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)
       {
           // If desired, output an error message to `stderr` here  
           goto cleanup;
       }
    
       use(space);
    
    cleanup:
       free(space);
       space = NULL;