memcpy and memmove in C
Level 5258 keystrokes
Copies a string with memcpy and with memmove, then uses memmove inside the same buffer to copy "Hello" over "World". It prints Hello, World! twice and then Hello, Hello!; memmove would stay safe even if the regions overlapped.
C code
// The source string: 13 characters plus '\0'1char src[] = "Hello, World!";// Destination buffer for memcpy2char dest1[20];// Destination buffer for memmove3char dest2[20];4 // memcpy copies bytes fast but is undefined if the regions overlap// strlen + 1 also copies the terminating '\0'5memcpy(dest1, src, strlen(src) + 1);// Prints memcpy: Hello, World!6printf("memcpy: %s\n", dest1);7 // memmove gives the same result here and also handles overlapping regions correctly8memmove(dest2, src, strlen(src) + 1);// Prints memmove: Hello, World!9printf("memmove: %s\n", dest2);10 // Copies "Hello" (bytes 0-4) over "World" (bytes 7-11) in the same buffer// These ranges do not overlap, but memmove would also be safe if they did11memmove(src + 7, src, 5);// The '!' at byte 12 is untouched: prints overlap: Hello, Hello!12printf("overlap: %s\n", src);Output
memcpy: Hello, World! memmove: Hello, World! overlap: Hello, Hello!
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this C code and how often they appear.
,× 10;× 9"× 8(× 8)× 8:× 3[× 3]× 3\× 3%× 3