[英]Confusion about strcat with memcpy
Okay so I have seen a few implementations of the strcat function with memcpy. 好的,所以我已经看到了memcpy的strcat函数的一些实现。 I understand that it is efficient, since there no need to allocate.
我知道这是有效的,因为不需要分配。 But how do you preserve overwriting the contents of the source string with the resultant string.
但是如何保留用结果字符串覆盖源字符串的内容。
For example lets take-: 例如让-
char *str1 = "Hello";
char *str2 = "World";
str1 = strcat(str1, str2);
How do I ensure that in str2
isn't overwritten with the contents of the resultant "HelloWorld" string ? 如何确保在
str2
中不会被生成的“ HelloWorld”字符串的内容覆盖?
Also if strings are nothing but char arrays, and arrays are suppose to have a fixed size then without reallocation of memory if I copy bytes into the array that are larger than the array , then isn't that unsafe ? 另外,如果字符串不过是char数组而已,并且数组应该具有固定的大小,那么如果我将比数组大的字节复制到数组中,则无需重新分配内存,那不是不安全吗?
It's not about unsafe , it's undefined behavior . 这不是不安全 ,而是不确定的行为 。
First of all, you're trying to modify a string literal , which inherently invokes UB. 首先,您尝试修改一个字符串常量 ,它固有地调用UB。
Secondly, regarding the size of the destination buffer, quoting the man page ( emphasis mine ) 其次,关于目标缓冲区的大小,引用手册页 ( 强调我的 )
The
strcat()
function appends thesrc
string to thedest
string, overwriting the terminating null byte ('\\0'
) at the end ofdest
, and then adds a terminating null byte.所述
strcat()
函数追加src
字符串到dest
串,覆盖终止空字节('\\0'
在结束时)dest
,然后添加终止空字节。 The strings may not overlap, and thedest
string must have enough space for the result.字符串可能不会重叠, 并且
dest
字符串必须具有足够的空间以容纳结果。 Ifdest
is not large enough, program behavior is unpredictable;如果
dest
不够大,则程序行为是不可预测的; [...][...]
I understand that it is efficient, since there no need to allocate.
我知道这是有效的,因为不需要分配。
That's an incorrect understanding. 这是一个错误的理解。 Neither
memcpy
nor strcat
allocates memory. memcpy
和strcat
都不分配内存。 Both require that you pass pointers that point to sufficient amount of valid memory. 两者都要求您传递指向足够数量的有效内存的指针。 If that is not the case, the program is subject to undefined behavior.
如果不是这种情况,该程序将受到未定义的行为的影响。
Your posted code is subject to undefined behavior for couple of reasons: 您发布的代码会受到不确定的行为的影响,原因如下:
str1
points to a string literal, which is in read-only portion of the program. str1
指向字符串文字,它位于程序的只读部分。
str1
does not enough memory to hold the string "HelloWorld"
and the terminating null character. str1
没有足够的内存来容纳字符串"HelloWorld"
和终止的空字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.