Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Warning C4701 is sometimes suppressed when compiling with /RTC1

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.

like image 542
Georgy Pashkov Avatar asked Feb 13 '16 11:02

Georgy Pashkov


1 Answers

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.

like image 182
Jesper Juhl Avatar answered Nov 16 '22 16:11

Jesper Juhl