【发布时间】:2010-09-12 14:55:53
【问题描述】:
给定:
char test[] = "bla-bla-bla";
两者哪个更正确?
char *test1 = malloc(strlen(test));
strcpy(test1, test);
或
char *test1 = malloc(sizeof(test));
strcpy(test1, test);
【问题讨论】:
-
注意:
strlen(test) != sizeof test。区别在于1.终止的'\0'不计入strlen(),而是计入sizeof。 -
虽然 sizeof() 在这种情况下有效,但我不鼓励将其用于这种类型的操作,因为数组很容易衰减为指针,除非你小心,否则你可能会被这个抓住。
-
为了内存边界安全,更喜欢
strncpy()而不是strcpy()。