这个函数有问题吗?
我看到网上有这样一道题目:
函数如下
void test1()
{
char a[10];
char* str1 = "0123456789";
strcpy( a, str1 );
}
====================
解答如下:
字符串str1需要11个字节才能存放下(包括末尾的’\0’),而string只有10个字节的空间,strcpy会导致数组越界;
========================================================================================================
可是我认为:a是数组,并不要求最后一个字符是‘\0'结束符。而且strcpy并不会复制'\0'给对象a。
所以这个函数是没有问题的。
对吗?请指教
[解决办法]
char * strcpy ( char * destination, const char * source );
Copy string
Copies the C string pointed by source into the array pointed by destination, including the terminating null character.
To avoid overflows, the size of the array pointed by destination shall be long enough to contain the same C string as source (including the terminating null character), and should not overlap in memory with source.
[解决办法]
strcpy是要复制'\0'给a的。而且C语言没有数组防越界检查,strcpy根本就不会管给它的数组有多大。
[解决办法]