Why does MSVC optimize away this memcpy call?

What you do is perfectly legal, this is definitely a bug in MSVC.

Here is a stripped down version to file a bug report:

#include <string.h>

extern unsigned char buffer[], *s;

void myfn() {
    memcpy(buffer + *buffer + 1, s + 1, *s);
    *buffer = 1;
}

Compiles to:

void myfn(void) PROC                                 ; myfn, COMDAT
        mov     BYTE PTR unsigned char * buffer, 1
        ret     0
void myfn(void) ENDP                                 ; myfn

Removing the statement *buffer = 1; prevents the code generation bug.
Check it on Godbolt's Compiler Explorer.


I think this is a bug in MSVC as what you are doing is legal.

Note that there has been a similar bug filed already titled: Release build with speed optimize leaves an array uninitialized.

The code given to reproduce the problem in the bug report also uses an extern type array[];

As per the team, this issue is fixed in an upcoming release (which is not mentioned).

Tags:

C++

C