This must be a very simple question, but I'm finding it weirdly hard to search for the answer.
In C, I've written the following strncpy
-like function:
int mystrncpy(char* s, char* t, int n) {
// copies at most n characters of t into s, assuming s is long enough
while (n > 0 && (*t != 0)) {
*(s++) = *(t++);
n--;
}
// at this point, either n=0 (in which case we ran out of string to copy)
// or *t = 0 (in which case we now need to null-terminate the string)
*s = 0;
return 0;
}
(It differs from strncpy
in that it always ensures s
is null-terminated at the end, and its arguments have been swapped around relative to strncpy
.)
Now, if I call it as follows:
int main() {
char s[5] = "hello";
char* t = "oppagangnamstyle";
mystrncpy(s, t, 10);
printf("%s\n", s);
return 0;
}
I expected to get some kind of "attempted to access element 5 of s
" error, because s
is allocated to be only five characters long.
What actually happens is that "oppagangna" is printed, and the program returns with exit code 0
.
When I step through with the debugger, in mystrncpy
, the character s
points to is successively 'h', 'e', 'l', 'l', 'o', '\0', '\0', …
Is it just fluke (or, which comes to the same thing, the compiler/operating system being unexpectedly nice to me) that s
happens to have zeros after it in memory, which are happy to be filled with more elements during the execution of mystrncpy
? Or have I misunderstood something else?