0

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.

Govind Parmar
  • 20,656
  • 7
  • 53
  • 85
Scene
  • 489
  • 4
  • 16
  • 2
    Read the [documentation](https://learn.microsoft.com/en-us/cpp/code-quality/c6011?view=msvc-160): *This warning indicates that your code dereferences a potentially null pointer.* – kaylum Feb 08 '21 at 22:53
  • Well, that solves it then. I should probably read the docs before anything. Thanks anyway! – Scene Feb 08 '21 at 22:54
  • @SeanXie "*Does the warning really mean that solAddr may be NULL*" Yes, that's how [`malloc`](https://en.cppreference.com/w/c/memory/malloc) indicates failure. If your "*text states otherwise*" then that text is either incomplete or plain wrong. – dxiv Feb 08 '21 at 22:59

1 Answers1

1

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;
Govind Parmar
  • 20,656
  • 7
  • 53
  • 85