[英]How to copy with 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).我尝试使用memcpy
,但我的程序无法正常工作(复制错误,但valgrind
未显示错误)。
But when I use two for
loops instead, it works properly, but than valgrind
shows an error但是当我改用两个for
循环时,它可以正常工作,但是valgrind
显示错误
uninitialised value was created by a heap allocation.未初始化的值是由堆分配创建的。
How to use properly memcpy
in this case?在这种情况下如何正确使用memcpy
?
memcpy(num, num1, length1);
memcpy(num + length1, num2, length2 + 1);
Your program has multiple issues:您的程序有多个问题:
malloc
failed is useless (but harmless).当malloc
失败时释放 null 指针是无用的(但无害)。length1 + length2 + 1
bytes, which is most likely too large as you intend to copy from index
in the second string.您分配length1 + length2 + 1
个字节,这很可能太大,因为您打算从第二个字符串中的index
复制。size_t
for the lengths and offsets.您应该使用类型size_t
作为长度和偏移量。num2 + index
without checking that index
is a valid offset inside the string num2
.您从num2 + index
复制而不检查index
是否是字符串num2
内的有效偏移量。Here is a modified version:这是修改后的版本:
#include <stdlib.h>
#include <string.h>
char *concat(const char *num1, const char *num2, size_t index) {
size_t length1 = strlen(num1);
/* skip index bytes in num2 */
while (index --> 0 && *num2)
num2++;
size_t length2 = strlen(num2);
char *num = malloc(length1 + length2 + 1);
if (num != NULL) {
size_t j = 0;
while (*num1) {
num[j++] = *num1++;
}
while (*num2) {
num[j++] = *num2++;
}
num[j] = '\0';
}
return num;
}
and using memcpy
:并使用memcpy
:
#include <stdlib.h>
#include <string.h>
char *concat(const char *num1, const char *num2, size_t index) {
size_t length1 = strlen(num1);
/* skip index bytes in num2 */
while (index --> 0 && *num2)
num2++;
size_t length2 = strlen(num2);
char *num = malloc(length1 + length2 + 1);
if (num != NULL) {
memcpy(num, num1, length1);
memcpy(num + length1, num2, length2 + 1);
}
return num;
}
concat
returns a pointer to an allocation array. concat
返回指向分配数组的指针。 It is the responsibilty of the caller to free this object after use.调用者有责任在使用后释放此 object。 For example:例如:
#include <stdio.h>
int main() {
char *p = concat("Hello", "dear world", 4);
if (p != NULL) {
printf("%s\n", p);
free(p);
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.