'\0' 结尾的 C 字符串

C string at the end of '\0'

在写c代码的时候,我试着写strcpy我自己的代码,我遇到了这个问题。

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

感谢 s.o 上的 this question,我知道字符串应该以 '\0' 结尾,但为什么上面的代码不起作用,即使它在执行时不会导致错误宣布? (当 char b[10] = "123456789" 时效果很好)

那么,“\0”到底是如何影响这个过程并最终导致错误的? (运行时?编译时?等) (我只知道'\0'应该是字符串的结尾)

char b[10] = "1234567890"; 不包含 NUL 终止符所以

while ((*s++ = *t++));

没有正确终止(正式的程序行为是 undefined)。注意常量 "1234567890"char[11] 类型;编译器允许您将它分配给一个较小的数组,并自动删除元素。

在行 char b[10] = "1234567890"; 上,字符串文字 "1234567890" 恰好是 10 个字符 + 1 个空终止符。数组中没有剩余空间,因此不会以 null 结尾。

通常情况下,编译器会警告您提供的初始化程序太大,但这种特定情况是一个非常特殊的陷阱。在 C 标准的初始化规则中,我们发现了这个邪恶的小规则(C17 6.7.9 §14,强调我的):

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.

你的情况没有空间,所以你没有得到空字符。由于这个奇怪的小规则,编译器也不会发出警告,因为代码符合 C 标准。