gpt4 book ai didi

C - 带有 char * 且长度大于源字符串长度的 memcpy

转载 作者:行者123 更新时间:2023-12-04 01:09:52 26 4
gpt4 key购买 nike

我现在在 C 中有以下代码

int length = 50
char *target_str = (char*) malloc(length);
char *source_str = read_string_from_somewhere() // read a string from somewhere
// with length, say 20
memcpy(target_str, source_str, length);

场景是target_str初始化为50字节。 source_str 是一个长度为 20 的字符串。

如果我想将 source_str 复制到 target_str 我使用 memcpy() 如上所述,长度为 50,这是 target_str。我在 memcpy 中使用 length 的原因是,source_str 可以具有 length 的最大值,但通常小于该值(在上面例如它的 20)。

现在,如果我想根据终止字符 ('\0') 复制直到 source_str 的长度,即使 memcpy 长度大于终止字符,上面的代码是正确的方法吗?或者是否有其他建议。

感谢您的帮助。

最佳答案

The scenario is that target_str is initialized with 50 bytes. source_str is a string of length 20.

If I want to copy the source_str to target_str i use memcpy() as above with length 50, which is the size of target_str.

目前您要求 memcpy 在源字符串结束后读取 30 个字符,因为它不关心源上可能存在的空终止符,这是一种未定义的行为

因为你复制一个字符串你可以使用 strcpy 而不是 memcpy

但是大小的问题可以反过来,我的意思是目标可以小于源,如果没有保护,你将再次出现未定义的行为

所以你可以使用 strncpy 给出目标的长度,只需注意添加最终空字符的必要性,以防目标小于源:

int length = 50
char *target_str = (char*) malloc(length);
char *source_str = read_string_from_somewhere(); // length unknown

strncpy(target_str, source_str, length - 1); // -1 to let place for \0
target_str[length - 1] = 0; // force the presence of a null character at end in case

关于C - 带有 char * 且长度大于源字符串长度的 memcpy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55838504/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com