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 ?
This is very much a false positive and still exists even in MSVC 2019. There is no way that the t.p
variable could be uninitialised.
In fact, there is no way it could reach the free()
statement without it being initialised to a non-NULL value. But, even if you allow for the possibility the compiler doesn't know that the exit()
function won't return, that's actually irrelevant, Whether it returns or not, the structure would still be initialised to something and, in any case, it's perfectly legal to free(NULL)
.
Removing the if .. exit
has no effect on the warning so I doubt that's the issue. It's more likely that this is just MSVC being aggressive in reporting warnings and the best way to stop it from bothering you is to simply ignore it.
By that, I don't mean you ignoring the warning (I could never do that given my nature), I mean telling MSVC to shut up about it:
while (1) {
MyStruct t = Test();
// MSVC wrongly reports this as using uninitialised variable.
#pragma warning(push)
#pragma warning(disable: 6001)
free(t.p);
#pragma warning(pop)
}