So in my program, I am trying to edit the elements of the original array "frags", which initially, have allocated strings stored in some slots. But I'm not exactly sure how. Over the course of the program, I need to reallocate elements in my original array so that they can store strings of greater length, but my approach seems to be leading to valgrind + functional errors. Valgrind says the error is coming from realloc, and the functional error is that the output is incorrect.
int main(void) {
char *frag[3];
char *frag1 = malloc(4), *frag2 = malloc(5);
strcpy(frag1, "him");
strcpy(frag2, "hers");
frag[0] = frag1;
frag[1] = frag2;
char *k = frag[0];
char *l = frag[1];
k = realloc(k, 500);
strcat(k, l);
printf("%s\n ", frag[0]);
printf("%s\n ", frag[1]);
free(k);
free(l);
return 0;
}
I'm not 100% clear on how malloc and realloc work when you assign them to different variables. If you do
char *k = malloc(5);
char *l = k;
l = realloc(l, 100);
Are you reallocating the memory which is still pointed to, by k? Will changes in freeing and rellocating pointer "l" affect content of pointer "k"? Sorry, I am new to C.