This piece of code (note the commented line):
#include <malloc.h>
#pragma warning(error: 4701)
int main(){
char buffer[1024];
//buffer[0] = 0;
void *p;
int size = 1;
if (size < 2)
p = malloc(size);
free(p); // C4701
return 0;
}
Gives the following warning (as expected):
f:\d\warning.cpp(13) : error C4701: potentially uninitialized local variable 'p' used
However, when I uncomment the assignment in main()
, the warning is no longer given. I am compiling with /RTC1
command line option to enable run-time error checks:
cl.exe /RTC1 warning.cpp
I've tried the latest 64-bit versions of compilers from Visual C++ 2013 and 2015. Both are producing the same behaviour.
Question is: is this a compiler bug, or is there an explanation for this? Microsoft's documentation mentions that /RTC1 might give run-time error in places where C4701 is given, but it says nothing about the warning being suppressed.
EDIT: The puzzling part is that the warning disappears only when buffer[0] = 0;
is not in comment.
There are many situations where something is sub-optimal, probably buggy or even undefined where the compiler has a very hard time detecting this. Thus, you should not rely on warnings (and/or runtime errors triggered by compiler instrumentation) to give you the complete truth.
Know that the compiler may warn when you do something stupid. It also may generate code to blow up at runtime when you do something stupid. Just never rely on that. It can't detect everything and you have to know the rules yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With