为什么以下C代码使用strcpy对我来说很好?我尝试以两种方式使其失败:
1)我尝试strcpy从字符串文字到分配的内存太小而不能包含它.它复制了整件事并且没有抱怨.
2)我尝试strcpy了一个未被NUL终止的数组.在strcpy与printf工作就好了.我原本以为strcpy复制了chars直到NUL找到了,但没有一个存在,它仍然停止.
为什么不这些失败?我是以某种方式获得"幸运",还是我误解了这个功能是如何工作的?它是特定于我的平台(OS X Lion),还是大多数现代平台以这种方式工作?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char *src1 = "123456789";
char *dst1 = (char *)malloc( 5 );
char src2[5] = {'h','e','l','l','o'};
char *dst2 = (char *)malloc( 6 );
printf("src1: %s\n", src1);
strcpy(dst1, src1);
printf("dst1: %s\n", dst1);
strcpy(dst2, src2);
printf("src2: %s\n", src2);
dst2[5] = '\0';
printf("dst2: %s\n", dst2);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
运行此代码的输出是:
$ ./a.out …Run Code Online (Sandbox Code Playgroud)