strcat中,字符串长度定义差异导致的结果不同
程序代码:
#include <stdio.h> #include <string.h> int main(void) { char name[8] = "I like "; //如果使用char *name = "I like ";,也会出现同样结果。 char *string = "C programming.\n"; printf("%s\n%ld\n", name, strlen(name)); strcat(name, string); printf("%s%ld\n", name, strlen(name)); return 0; }执行结果(这是在linux下执行的结果):
I like
7
I like C programming.
22
*** stack smashing detected ***: ./test terminated
已放弃 (核心已转储)
7
I like C programming.
22
*** stack smashing detected ***: ./test terminated
已放弃 (核心已转储)
程序代码:
#include <stdio.h> #include <string.h> int main(void) { char name[9] = "I like "; char *string = "C programming.\n"; printf("%s\n%ld\n", name, strlen(name)); strcat(name, string); printf("%s%ld\n", name, strlen(name)); return 0; }执行结果:
I like
7
I like C programming.
22
向strcat传递的第一个字符串必须足以容纳第二个字符串,所以*name和name[8]都会出错,但是name[9]明显不足一容纳string,但是却正常执行。这是为什么呢?7
I like C programming.
22
[ 本帖最后由 gleerat 于 2013-1-9 11:46 编辑 ]