Unlogical C6001 warning: Using uninitialized memory warning in C with Visual Studio

白昼怎懂夜的黑 提交于 2021-02-09 06:56:47

问题


Given this code:

#include <stdlib.h>

typedef struct
{
    int *p;
} MyStruct;

MyStruct Test()
{
    MyStruct ms;
    ms.p = malloc(sizeof(int) * 5);
    if (!ms.p) exit(-1);
    return ms;
}

int main(void)
{
    while (1)
    {
        MyStruct t = Test();
        free(t.p); // C6001: Using uninitialized memory 't.p'.
    }
}

Visual Studio shows C6001 warning on the free call line. However, I see there is no way to achieve the free line with the memory t.p uninitialized. What am I missing ?


回答1:


Some points:

  1. sometimes SAL warnings can be "treated" by having malloc() replaced by calloc()

a) much more precise (element size and count params provided) - better analyzer prediction?

b) different API - that one possibly not instrumented, thus no analyzer output? ;-P

  1. analysis might be confused via the exit() within that function, which smells a bit like being related to [missing] noreturn attribution (this case very similar to bailing out of a return-value-based function via exception throw), see e.g. https://en.cppreference.com/w/cpp/language/attributes ; OTOH the noreturn attribution thing is conditional here (i.e., not in all code paths), thus a noreturn attribution smells imprecise/wrong (the code is trying to use a function result after all)

  2. generally, try to aggressively "break" things into achieving "working" warning-free behaviour, by progressively removing (potentially larger) pieces of the implementation until it starts to "work". E.g. in this case, removing the exit() line may cause changed SAL behaviour and thus provide clues as to what aspect actually is the "problem".

  3. perhaps the design might be less optimal than possible - in such cases, possibly some limited rework might lead to more "obvious"/"elegant"/"modern" handling which may result in not producing such SAL warnings.



来源:https://stackoverflow.com/questions/59238295/unlogical-c6001-warning-using-uninitialized-memory-warning-in-c-with-visual-stu

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!