I recently had a question from an interview where I had to implement memcpy. I used memcpy a lot in my experience, so this did not seem like a difficult problem.
So, I started implementing a loop to copy one address at a time from pointer to pointer, something like this:
void memcpy(void* dest, void* src, int size){ for(int index = 0; index < size; index++){ dest[index] = src[index]; } }
However, the interviewers interrupted, noting that the memcpy man page says that โcopy n bytes from src to destโ (which I confirmed later), and then wanted me to iterate over the size / 4 instead, and then take the remaining index loop with another <size% 4 (I assume it was a 32-bit system?)
Well, that seemed strange, since I used memcpy for many years without any problems, without giving it a modifier * 4). When I got home, I ran gdb and copied a small โhelloโ line and tried to enter the size using both strlen () and the constants to see where it starts and stops.
char* src = "hello"; char* dest = calloc(16, sizeof(char)); int len = strlen(src); memcpy(dest, src, len);
Now I have carefully studied src and dest with gdb, in which both contained "hello \ 0".
So my question is: what I do not understand about using the number 4 (or "size in bytes")? And why does the documentation say "n bytes" when this is not really behavior? What I donโt see here?
c ++ c
Vaporwarewolf
source share