Search code examples
carraysstringmallocrealloc

Editing Elements of Original Array, Valgrind and Functional Error


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.


Solution

  • 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.
    

    After

    char *k = malloc(5); 
    char *l = k;
    l = realloc(l, 100); 
    

    k maybe still point l, maybe not . If k did't pointer l ,then l was already freed by realloc.

    when you use realloc. It will try to get memory base on the old memory address, if that success, k still point l.While, if there don't have enough memory .realloc will get a new memory, whoes address is total different with the old one, and copy the datas from old memory to new.Then it will free the old memory .