为什么VS2013抱怨"使用未初始化的内存"?

sth*_*ago 7 c pointers visual-studio-2013

我有一个代码如下:

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

typedef struct {
    char *a;
    char *b;
    int c;
} my_type;

void free_my_type(my_type *p) {
    if (p) {
        if (p->a) free(p->a);  // line 12
        if (p->b) free(p->b);  // line 13
        free(p);
    }
}

int main(void) {
    my_type *p = malloc(sizeof(*p));

    p->a = malloc(10);
    p->b = malloc(10);
    p->c = 10;

    free_my_type(p);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

VS的代码分析抱怨我是:

"C6001 Using uninitialized memory '*p'"

        '*p' is not initialized                             12
        Skip this branch, (assume 'p->b' is false)          13
        '*p' is used, but may not have been initialized     13
Run Code Online (Sandbox Code Playgroud)

我的意思是,它是一个指针,我正在检查它是否是NULL.我怎么知道*p是否被初始化?

奇怪的是,如果结构中只有一个其他指针 - char *a例如 - 仅警告不会触发.如果我free(p->b)之前做过,它也不显示free(p->a)(交换第12和13行).

HDJ*_*MAI 3

好像是Visual Studio 2013的分析器工具的问题

正如这里所解释的:

https://randomascii.wordpress.com/2011/07/25/analyze-for-visual-studiothe-ugly-part-1/

https://randomascii.wordpress.com/2011/07/29/analyze-for-visual-studiothe-ugly-part-2/

https://randomascii.wordpress.com/2011/08/06/analyze-for-visual-studiothe-ugly-part-3-false-positives/

https://randomascii.wordpress.com/2011/08/20/analyze-for-visual-studiothe-ugly-part-4-false-negatives/

https://randomascii.wordpress.com/2011/09/13/analyze-for-visual-studio-the-ugly-part-5/

作为第 5 部分的更新,我们可以阅读以下内容:

更新:幸运的是,VC++ 2013 已经解决了其中许多问题,但 __analysis_assume 的问题仍然存在。

因此,即使他们使用最新的 Visual Studio 版本解决了许多警告问题,分析器工具中仍然会出现一些错误。

用VS2015 Enterprise测试:给出同样的问题

在此输入图像描述

  • 我删除了 ifs(现在我知道 free 会自行检查),并且它抑制了针对此特定情况的警告。不过,还有其他误报情况。 (2认同)