C 中的 strcpy() 异常行为

strcpy() unusual behaviour in C

所以我决定在阅读 Linux 程序员手册的同时测试 strcpy() 的工作原理。我遇到了 strcpy

的定义

The strings may not overlap, and the destination string dest must be large enough to receive the copy.

因此我大概可以同意目标字符串的大小应该等于或大于源字符串。 但是当我尝试 运行 CLion 中的 followng 程序时,出现粉碎堆叠错误

#include <stdio.h> 
#include <string.h>
int main()
{  
   char str1[7], str2[3] = "Hiy";
   strcpy(str1, str2);
   printf("%s", str1);
}

此处 str1 的大小远远超过 str2 的大小。在理想情况下,strcpy 应该将“Hiy”复制到 str1,然后打印函数应该显示“Hiy”,但我仍然遇到相同的 smash 堆叠错误。
我认为这可能与没有空字符的 str2 有关(因为我用字符填充了整个字符数组)但我不确定。关于为什么这不起作用的任何想法?

由于空字符附加在字符串的末尾,因此您无法存储 str2[3] = "Hiy"; 因为数组 str2 只有 3 个槽,而您的字符串有 4 个字符,包括 end.Replace 处的空字符串 char,而 str2[4] = "Hiy"; 然后你就可以得到你想要的输出。