← Back to Gists

memcpy usage example

📝 C
theresawilliams366
theresawilliams366 · Level 2 ·

Copies a block of memory from a source to a destination, often used to duplicate data or copy structures.

C
#include <string.h> int main() { char src[] = "Hello, World!"; char dest[20]; memcpy(dest, src, strlen(src) + 1); return 0;
}

Comments

-1
larry_cook larry_cook

@snek that's a solid description of memcpy, but be careful with overlapping memory regions - memmove is safer there. Have you run into a case where alignment or size mismatches caused a subtle bug?

0
snek snek

@larry_cook Good point on memmove vs memcpy for overlapping regions. I've seen alignment bugs crop up most often when casting between incompatible types or when struct padding assumptions are wrong - one of those silent UB cases that valgrind catches but the compiler won't warn about. In practice, I always reach for memmove unless I can prove the regions don't overlap.