Dereferencing NULL pointer in C - Visual Studio 2019

Shervan360 1,661 Reputation points
2021-06-11T23:55:10.503+00:00

Hello,

How can I remove the warning?

Severity Code Description Project File Line Suppression State
Warning C6011 Dereferencing NULL pointer 'dArray+r'. C_Project02 C:\Users\My\source\repos\C_Project02\C_Project02\C_Project0e2.c 20

    int n; scanf_s("%d", &n);
    int** dArray = calloc(n, sizeof(int*));
    for (int r = 0; r < n; r++)
    {
        *(dArray + r) = calloc((r + 1), sizeof(int));
    }
C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,904 questions
{count} votes

Accepted answer
  1. WayneAKing 4,926 Reputation points
    2021-06-12T04:08:50.747+00:00

    In the description of the warning in the doc at the
    link provided by RLWA32:

    "This warning indicates that your code dereferences a
    potentially null pointer."

    the key word is "potentially". If calloc should fail
    then the pointer will be NULL, if it succeeds it
    won't be NULL. That will only be known at run time,
    and could be different at different times under
    varying circumstances. So the compiler has no way
    to tell what will happen at run time, but it
    can tell what might happen and is warning you
    of the possibility.

    As the doc also suggests, if you add code to verify
    that calloc has not failed then the compiler will
    suppress that warning. For example:

    int n; scanf_s("%d", &n);
    int** dArray = calloc(n, sizeof(int*));
    if(!dArray)
    {
        return -1;
    }
    for (int r = 0; r < n; r++)
    {
        *(dArray + r) = calloc((r + 1), sizeof(int));
    }
    

    or

    int n; scanf_s("%d", &n);
    int** dArray = calloc(n, sizeof(int*));
    if(dArray)
    {
        for (int r = 0; r < n; r++)
        {
            *(dArray + r) = calloc((r + 1), sizeof(int));
        }
    }
    
    • Wayne
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. RLWA32 47,966 Reputation points
    2021-06-12T01:07:54.967+00:00

    I suggest you read the guidance about validating a pointer before you use it in the documentation for the warning message. See c6011. What would happen if calloc failed?

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.