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?