问题描述
我有一个函数,它创建一个地址,在地址上连续存储值,然后返回地址:
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;
}
但是,我收到一条警告,指出Warning C6011 Dereferencing NULL pointer 'solAddr'
.经过一些在线搜索,我发现我只需要使用if"-语句确保 solAddr
不是 NULL
并且警告消失:
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;
}
警告真的意味着solAddr
可能是NULL
吗?似乎文字另有说明.该代码在使用和不使用 NULL
检查的情况下都可以使用,但我对这个警告真正想告诉我的内容感到困惑.
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.
推荐答案
是的,警告是存在的,因为如果分配失败,malloc
可能返回 NULL
.
Yes, that warning is there because malloc
could return NULL
if allocation failed.
这实际上是来自 SAL 注释应用于库标头,而不是 Visual Studio 本身.您应该始终检查 malloc
返回值是否为 NULL
并处理它,因为 malloc
could 返回 NULL
如果失败.我常用的方法是:
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;
这篇关于Visual Studio“取消引用空指针"警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!