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.
CodePudding user response:
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);
}