Last active
December 20, 2015 14:59
-
-
Save tetsuok/6151340 to your computer and use it in GitHub Desktop.
sayonara memcpy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| * The purpose of this program is to show you should always use memmove | |
| * instead of memcpy if there is no particular reason. | |
| * | |
| * This program intentionally copies overlapped memories, though. | |
| * | |
| * Try to compile with different optimizations, compilers, OSs. | |
| * | |
| * For example, | |
| * | |
| * $ gcc -O0 overlap.c && ./a.out | |
| * $ gcc -O2 overlap.c && ./a.out | |
| * $ gcc -O3 overlap.c && ./a.out | |
| * | |
| * $ clang -O0 overlap.c && ./a.out | |
| * $ clang -O3 overlap.c && ./a.out | |
| * | |
| * On OS X (10.8), Apple's LLVM 4.2 (clang-425.0.28) | |
| * gave different results of memcpy between -O0 and -O3. | |
| * | |
| * | |
| */ | |
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <string.h> | |
| static void copy_byte(void* (func)(void *dst, const void* src, size_t len)) { | |
| unsigned char* ptr; | |
| unsigned char* block; | |
| block = (unsigned char *)malloc(64); | |
| if (block == NULL) { | |
| fprintf(stderr, "out of memory.\n"); | |
| exit(1); | |
| } | |
| memset(block, 0, 64); | |
| block[17] = 0xffU; | |
| printf("block[%d] = 0x%x\n", 17, block[17]); | |
| ptr = block + 16; | |
| func(block, ptr, 32); | |
| printf("block[%d] = 0x%x\n", 17, block[17]); | |
| printf("block[%d] = 0x%x\n", 1, block[1]); | |
| free(block); | |
| } | |
| int main() { | |
| printf("memmove:\n"); | |
| copy_byte(memmove); | |
| printf("\nmemcpy:\n"); | |
| copy_byte(memcpy); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment