9.3 Unrestricted String Functions
The most commonly used string functions are ʺunrestricted,ʺ meaning that they determine the length of their string arguments solely by looking for the terminating NUL byte. When using these functions, it is the programmerʹs responsibility to make sure that the resulting string does not overflow the memory in which it is supposed to fit. This problem is described in more detail for each of the functions discussed in this section.
最常用的字符串函数都是"不受限制"的,就是说它们只是通过寻找字符串参数结尾的NUL字节来判断它的长度。这些函数一般都指定一块内存用于存放结果字符串。在使用这些函数时,程序员必须保证结果字符串不会溢出这块内存。在本节具体讨论每个函数时,我将对这个问题作更详细的讨论。
9.3.1 Copying Strings
Strings are copied using strcpy whose prototype is shown below.
用于复制字符串的函数是strcpy ,它的原型如下所示:
char *strcpy( char *dst, char const *src );
This function copies the string from the src argument into the dst argument If the src and dst arguments overlap, the result is undefined. Because it is modified, dst must be a character array or a pointer to an array or to dynamically allocated memory. A string literal may not be used. The function returns a value, which is described in Section 9.3.3.The previous contents of the destination argument are overwritten and are lost.Even if the new string is shorter than the old contents of dst, the last characters of the previous string are effectively erased because they appear after the terminating NUL byte of the new string.
这个函数把参数src 字符串复制到dst 参数。如果参数src 和dst 在内存中出现重叠,其结果是未定义的。由于dst 参数将进行修改,所以它必须是个字符数组或者是一个指向动态分配内存的数组的指针,不能使用字符串常量。这个函数的返回值将在9.3.3 小节描述。目标参数的以前内容将被覆盖并丢失。即使新的字符串比dst 原先的内存更短,由于新字符串是以NUL 字节结尾,所以老字符串最后剩余的几个字符也会被有效地删除。
Consider this example:
考虑下面这个例子:
char message[] = "Original message";
...
if( ... )
strcpy( mesaage, "Different" );
If the condition is true and the copy is performed, the array will contain the following:
如果条件为真并且复制顺利执行,数组将包含下面的内容:
The characters after the first NUL byte are never accessed by the string functions and are, for all practical purposes, lost.
第1 个NUL 字节后面的几个字符再也无法被字符串函数访问,因此从任何现实的角度看,它们都已经是丢失的了。
It is up to the programmer to make sure that the destination array is large enough to hold the string. If the string is longer than the array, the excess characters will be copied anyway and will overwrite whatever values happen to be after the array in memory, strcpy is unable to avoid this problem because it cannot determine the size of the destination array. For example:
程序员必须保证目标字符数组的空间足以容纳需要复制的字符串。如果字符串比数组长,多余的字符仍被复制,它们将覆盖原先存储于数纽后面的内存空间的值。strcpy 无法解决这个问题,因为它无法判断目标字符数组的长度。
char message[] = "Original message";
...
strcpy( message, "A different message" )
The second string is too long to fit in the array, so the strcpy will run off the end of the array and overwrite whatever variables happen to follow it in memory. You can avoid a lot of debugging by making sure that the destination argument is large enough before calling strcpy.
第2 个字符串太长了,无法容纳于message 字符数组中。因此,strcpy 函数将侵占数组后面的部分内存空间,改写原先恰好存储在那里的变量。如果你在使用这个函数前确保目标参数足以容纳源字符串,就可以避免大量的调试工作。