问题
While writing c code, I tried to write strcpy
code of my own, and I faced this issue.
#include <stdio.h>
#include <string.h>
void strcpy2(char *s, char *t);
int main() {
char a[10] = "asds";
char b[10] = "1234567890";
strcpy2(a, b);
printf("Copy completed! : %s", a);
return 0;
}
void strcpy2(char *s, char *t) {
while ((*s++ = *t++));
}
Error code : Process finished with exit code -1073741819 (0xC0000005)
Thanks to this question on the s.o, I learned string should ends with '\0', but why the above code doesn't work even though it does not cause error when it is declared? (It worked well when char b[10] = "123456789")
So, How exactly '\0' affects this process and eventually cause the error? (Runtime? Compile time? etc) (I only know '\0' should be the end of the string)
回答1:
On the line char b[10] = "1234567890";
, the string literal "1234567890"
is exactly 10 characters + 1 null terminator. There is no room left in the array, so it doesn't get null terminated.
Normally, the compiler would warn you for providing an initializer which is too large, but this specific case is a very special pitfall. In the C standard's rules for initialization, we find this little evil rule (C17 6.7.9 §14, emphasis mine):
An array of character type may be initialized by a character string literal or UTF−8 string literal, optionally enclosed in braces. Successive bytes of the string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.
There is no room in your case, so you don't get a null character. And because of this weird little rule, the compiler doesn't warn against it either, because the code conforms to the C standard.
回答2:
char b[10] = "1234567890";
doesn't contain a NUL-terminator so
while ((*s++ = *t++));
does not terminate correctly (formally the program behaviour is undefined). Note that the constant "1234567890"
is a char[11]
type; the compiler allows you to assign it to a smaller array, with elements removed automatically.
来源:https://stackoverflow.com/questions/52385351/c-string-at-the-end-of-0