Very basic one, not handling edge cases or optimization.
- in C sizeof(char) == 1 by definition, so copying by char-sized units copies byte
- for non-overlapping regions only
- needs to be unsigned char because plain char is signed depending on platform. eg. raw bytes 0x00, 0x80, 0xFF can be converted to
signed: 0, -128, -1.
unsigned: 0 128 255
#include <stddef.h>
void *memcpy(void *dest, const void *src, size_t count) {
unsigned char *d = (unsigned char *) dest;
const unsigned char *s = (const unsigned char *) src;
for (size_t i = 0; i < count; i++) {
d[i] = s[i];
}
}
If dest starts after src and ranges overlap, copying forwards will overwrite bytes you still need from src.
Solution: copy to a temp buffer and then to dest.
Or copy backwards