问题
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:
- 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
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)
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".
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