如何用memcpy复制?
char *concat(char *num1, const char *num2, int index) {
int length1 = strlen(num1);
int length2 = strlen(num2);
int lengthNum = 0;
char *num = malloc(length1 + length2 + 1);
if (num == NULL) {
free(num);
return NULL;
}
// memcpy(num, num1, length1);
// memcpy(num + length1, num + index, length2 + 1);
for (int i = 0; i < length1; i++) {
num[lengthNum] = num1[i];
lengthNum++;
}
for (int i = index; i < length2; i++) {
num[lengthNum] = num2[i];
lengthNum++;
}
return num;
}
我尝试使用memcpy
,但是除了我的程序无法正常工作(副本错误,但valgrind
没有显示错误)。
但是,当我使用两个for
循环时,它可以正常工作,而是valgrind
显示错误
非初始化的值是由堆分配创建的。
在这种情况下,如何正确使用memcpy
?
char *concat(char *num1, const char *num2, int index) {
int length1 = strlen(num1);
int length2 = strlen(num2);
int lengthNum = 0;
char *num = malloc(length1 + length2 + 1);
if (num == NULL) {
free(num);
return NULL;
}
// memcpy(num, num1, length1);
// memcpy(num + length1, num + index, length2 + 1);
for (int i = 0; i < length1; i++) {
num[lengthNum] = num1[i];
lengthNum++;
}
for (int i = index; i < length2; i++) {
num[lengthNum] = num2[i];
lengthNum++;
}
return num;
}
I tried to use memcpy
, but than my program doesn't work correctly (copies wrongly, but valgrind
doesn't show an error).
But when I use two for
loops instead, it works properly, but than valgrind
shows an error
uninitialised value was created by a heap allocation.
How to use properly memcpy
in this case?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的程序有多个问题:
malloc
失败时,释放零指针是没有用的(但无害)。length1 + length2 + 1
字节,这很可能太大了,因为您打算从第二个字符串中的index
复制。size_t
用于长度和偏移。num2 + index
复制,而无需检查index
是字符串num2
内的有效偏移。这是一个修改后的版本:
和使用
memcpy
:concat
返回分配数组的指针。使用后,呼叫者的责任是释放此对象的责任。例如:Your program has multiple issues:
malloc
failed is useless (but harmless).length1 + length2 + 1
bytes, which is most likely too large as you intend to copy fromindex
in the second string.size_t
for the lengths and offsets.num2 + index
without checking thatindex
is a valid offset inside the stringnum2
.Here is a modified version:
and using
memcpy
:concat
returns a pointer to an allocation array. It is the responsibilty of the caller to free this object after use. For example: