假设我喜欢这样复制字符串。我可以复制空字符串中的字符串吗?
char str[] = "";
char *str2 = "abc";
strcpy(str, str2);
printf("%s", str); // "abc"
printf("%d", strlen(str)); // 3
然后,为什么它不给我未定义的行为或导致程序失败。这样做的缺点是什么?
假设我喜欢这样复制字符串。我可以复制空字符串中的字符串吗?
char str[] = "";
char *str2 = "abc";
strcpy(str, str2);
printf("%s", str); // "abc"
printf("%d", strlen(str)); // 3
然后,为什么它不给我未定义的行为或导致程序失败。这样做的缺点是什么?
此代码肯定会导致堆栈问题,尽管有这么小的字符串,但您没有看到问题。举个例子来说,以下几点:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char str[] = "";
char *str2 = "A really, really, really, really, really, really loooooooooooooooonnnnnnnnnnnnnnnnng string.";
strcpy(str, str2);
printf("%s\n", str);
printf("%d\n", strlen(str));
return 0;
}
一个人为的例子,是的,但运行此的结果是:
A really, really, really, really, really, really loooooooooooooooonnnnnnnnnnnnnnnnng string.
92
Segmentation fault
这就是为什么strcpy函数气馁的原因之一,而建议使用需要指定相关字符串大小的复制和连接函数。
您正在写入分配给堆栈中str的内存空间。你需要确保你有足够的str空间。在你提到的例子,你需要一个空间,b和c加上一个空字符结束的字符串,因此,此代码应工作:
char str[4];
char *str2 = "abc";
strcpy(str, str2);
printf("%s", str); // "abc"
printf("%d", strlen(str)); // 3
它可以使你不确定的行为,但你的程序没有按”因此不得不失败。这就是未定义行为的工作原理。
你怎么知道它不给你不确定的行为? –
,因为它给了我正确的字符串长度。 –
[未定义的行为意味着任何事情都可能发生](http://blogs.msdn.com/b/oldnewthing/archive/2011/09/29/10217910.aspx) – phihag