2015-11-04 435 views
6

我有一个是这样的代码:为什么VS2013抱怨“使用未初始化的内存”?

#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; 
} 

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 

我的意思是,这是一个指针,我检查,看它是否是NULL。我将如何知道* p是否已初始化?奇怪的是,如果结构中只有一个其他指针 - 例如char *a,则警告不会触发。如果我在free(p->a)之前free(p->b)(交换行12和13),它也不会显示出来。

+2

此代码看起来好像没什么问题,也许代码分析窃听。 –

+4

'如果(p-> a)'是多余的,如'free'执行此检查本身 –

+0

OOC,确实转换为'my_type * p = calloc(1,sizeof(* p));'停止警告?这应该不重要,但我想知道是否会压制警告。有可能它会假定异常提升行为或其他情况,并不是所有的指针都会在特定的条件下被初始化(在代码中不是很明显,但是很小的变化,比如分配'p-> b'成功分配' p-> a')可能会引发这种情况。 – ShadowRanger

回答

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企业:给出了同样的问题

enter image description here

+1

我删除了ifs(现在我知道免费做检查自己),它抑制了这个特定情况下的警告。还有其他一些误报,tho。 – sthiago

相关问题