Why does the C ++ compiler eliminate useless entries if there is no code after these entries?

I am testing Visual C ++ 10 optimization options and have found a rather interesting thing. All code here is compiled with / O 2.

In the following code:

int _tmain(int argc, _TCHAR* argv[]) { char buffer[1024] = {}; MessageBoxA( 0, buffer, buffer, 0 ); memset( buffer, 0, sizeof( buffer ) ); return 0; } 

calling memset() before return excluded from machine code (I am checking the disassembly). This is perfectly reasonable - if after that there is no reading from buffer , then memset() useless, and if developers really want to overwrite the buffer, you can use SecureZeroMemory() .

However, in the following code:

 int _tmain(int argc, _TCHAR* argv[]) { char buffer[1024] = {}; MessageBoxA( 0, buffer, buffer, 0 ); memset( buffer, 0, sizeof( buffer ) ); Sleep( 0 ); //<<<<<<<<<<<<<<<<<<<<<<<<<<< Extra code return 0; } 

the memset() call is not resolved. This call does not affect the observed behavior and can be eliminated in the same way as in the first fragment.

It may be a compiler flaw or it may be useful in some way - I cannot solve it.

Why can I leave the memset() call in the machine code emitted for the second fragment?

+6
source share
2 answers

The compiler probably cannot say that MessageBoxA does not create the alias buffer , which Sleep then uses. Thus, it does not perform an as-if check.

+18
source

The compiler can look at the contents of the memset and determine what it is doing. Sleep() is a system call interacting with the kernel, and its behavior depends on the version of Windows on which the code is executed; including the possibility of not yet implemented versions of Windows. The compiler simply does not know what the function will do, and therefore there is no way to optimize it.

The same can be said about MessageBox , which makes me wonder that memset deleted in the first version.

It is a safe bet that calling memset will not be a problem for any current or future version of Windows, but thatโ€™s not what I want the compiler to guess.

+2
source

Source: https://habr.com/ru/post/896405/


All Articles