Will compilers optimize memcpy calls when called with few bytes?
For this sample code:
#define _CRT_SECURE_NO_WARNINGS // To allow usage of scanf in vc++2015 #include <stdlib.h> #include <stdio.h> #include <string.h> int main() { // printf and scanf to prevent code elimination char bytes[ 4 ]; scanf( "%s", bytes ); char buffer[ 4 ]; memcpy( buffer, bytes, 4 ); printf( "%s", buffer ); return 0; }
Visual C ++ 2015 generated this team output (release build, x64):
; memcpy was replaced by a simple register move mov eax, DWORD PTR bytes$[rsp] lea rdx, QWORD PTR buffer$[rsp] ; setting arguments lea rcx, OFFSET FLAT: ??_C@ _02DKCKIIND@ ?$CFs?$AA@ ; for printf call ; at this point copied array was actually stored in memory mov DWORD PTR buffer$[rsp], eax call printf
So, modern compilers won't even call a procedure.
user4832129
source share