Learn C
#include "arraysstrings/mem_functions.h"

Raw Memory: memcpy, memset & memcmp in C

#concept

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.

#how it works
1

memcpy copies bytes

memcpy(dst, src, n * sizeof *dst); duplicates n elements β€” fast, unchecked, overlapping regions forbidden.

2

memmove tolerates overlap

Shifting elements within one buffer (deleting index i) needs memmove β€” memcpy would corrupt on overlap.

3

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.)

4

memcmp compares

memcmp(a, b, n) returns negative/zero/positive on raw bytes β€” equality reads as == 0, like strcmp.

#example
#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;
}
Output
3 0
1memcpy duplicates all 12 bytes (sizeof src) into dst β€” non-overlapping, fully valid.
2memset zeroes src in place, byte by byte.
3dst[2] kept 3 while src[0] reads 0 β€” copy then clear, verified.
#use cases
Duplicating arrays and structs with sized memcpy
Deleting elements by shifting tails with memmove
Zeroing buffers and fresh allocations with memset
Comparing binary blobs and hashes with memcmp

Recommended resourcesAffiliate links Β· may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice β€” pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from β€” great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C yourself β€” building beats watching.