简体   繁体   中英

Dereferencing NULL pointer in C

I am trying to allocate memory for 2 float vectors with a length of 1024 and fill them with some numbers. However, I get the warnings:

Dereferencing NULL pointer 'fpVec1', Dereferencing NULL pointer 'fpVec2'

For the lines in the for loop. The execution is fine, but I don't understand the warning. Am I doing something wrong?

int main(void){
int iLength = 1024;
int i, j;
float *fpVec1, *fpVec2, *fpVec3, *fpVec4;
fpVec1 = (float*)malloc(iLength * sizeof(float));
fpVec2 = (float*)malloc(iLength * sizeof(float));
fpVec3 = (float*)malloc(iLength * sizeof(float));
fpVec4 = (float*)malloc(iLength * sizeof(float));

for (i = 0; i < iLength;i++)
{
    fpVec1[i] = ((float)i) + 1024.0;
    fpVec2[i] = ((float)i) * 1.7;
}}

Edit: I am using Intel C++ Compiler 19. The warning is generated in Visual Studio 2019 Professional Edition. The warning disappeared when I used an if statement as in the accepted solution, to check the validity of the pointers.

According to this post if you check the values returned by malloc() before actually using the pointers, the warning will go away. The answer in that post isn't accepted unfortunately.

int main(void)
{
    int iLength = 1024;
    int i, j;
    float *fpVec1, *fpVec2;
    fpVec1 = (float*)malloc(iLength * sizeof(float));
    fpVec2 = (float*)malloc(iLength * sizeof(float));

    if (fpVec1 && fpVec2) {
        for (i = 0; i < iLength;i++)
        {
            fpVec1[i] = ((float)i) + 1024.0;
            fpVec2[i] = ((float)i) * 1.7;
        }
    }
    free(fpVec1);
    free(fpVec2);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM