cpointerslinspace

Linearly Spaced Array in C


I'm trying to replicate the linspace functions from Matlab and numpy (python) in C however, I keep getting the warning about dereferencing NULL pointer.

I'm very much a novice at C and having only worked in Matlab, python and lua before, pointers are quite something to try and wrap my head around!

#include <stdlib.h>
#include <stdio.h>
#include <math.h>

 double* linspace(double init, double fin, int N) {
     double *x;
     int i = 0;
     double step = (fin - init) / (double)N;
     x = (double*)calloc(N, sizeof(double));

     x[i] = init; /*<=== Line 14*/

     for (i = 1; i < N; i++) {
         x[i] = x[i - 1] + step;
     }
     x[N - 1] = fin;
     return x;
}

int main() {
    double *x_array = linspace(0, 10, 1000);

    printf(&x_array);

    free(x_array);
    return 0;
}

And I get the exact warning:

Warning C6011   Dereferencing NULL pointer 'x'. Line 14

Obviously I'm sure its just a rookie mistake but I'm unsure of how to sort it!

Thanks.


Solution

  • The following message:

    Warning C6011   Dereferencing NULL pointer 'x'. Line 14
    

    is not a runtime error. It is a very badly worded warning issued by the Microsoft C++ compiler (see https://learn.microsoft.com/en-us/cpp/code-quality/c6011?view=vs-2019) about the possibility that you might be dereferencing a pointer which might be NULL at runtime.

    Your pointer will be NULL if calloc() fails to allocate memory, an eventuality that you probably do not need to worry about, but to keep the compiler happy and prevent the warning, you might want to ASSERT() that the pointer is not NULL before proceeding to dereference the pointer.

    And if you want to write perfectly robust code, then you need to add code which makes your function gracefully fail if calloc() returns NULL.