Raw Memory: memcpy, memset & memcmp in C
Where string.h functions stop at terminators, <string.h>'s mem* family works on counted bytes: memcpy(dst, src, n) copies, memmove handles overlapping regions safely, memset fills with a byte value, and memcmp compares byte-wise returning negative/zero/positive. No terminators, no surprises β just explicit lengths.
The rules are absolute: regions must be valid for n bytes, memcpy with overlap is undefined (use memmove), and sizes come from sizeof expressions, never magic numbers. These four functions move nearly all bulk data in C programs.
memcpy copies bytes
memcpy(dst, src, n * sizeof *dst); duplicates n elements β fast, unchecked, overlapping regions forbidden.
memmove tolerates overlap
Shifting elements within one buffer (deleting index i) needs memmove β memcpy would corrupt on overlap.
memset fills
memset(buf, 0, n); zeroes n bytes β the standard buffer reset. (Only zeroing is portable per-byte; use loops for other fills of multibyte types.)
memcmp compares
memcmp(a, b, n) returns negative/zero/positive on raw bytes β equality reads as == 0, like strcmp.
#include <stdio.h>#include <string.h>Β int main(void) { int src[] = {1, 2, 3}; int dst[3] = {0}; memcpy(dst, src, sizeof src); memset(src, 0, sizeof src); printf("%d %d\n", dst[2], src[0]); return 0;}Recommended resourcesAffiliate links Β· may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself β building beats watching.