0

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.

pyrrhic
  • 1,769
  • 2
  • 15
  • 27
  • After your reallocation from `k = realloc(k, 500)`, this likely returns a different pointer value than the original `k`. But that original value for `k` *came* from `frag[0]` which is left unchanged. Once you do this the pointer *value* is no longer valid, an thus using it for dereference (the stmt `printf("%s\n ", frag[0]` does this) is undefined behavior. Note: `frag1` is in a similar state. Look closely for why. So yes, your final sample, `k` is no longer valid assuming `l` is returned a non-NULL value. This is, btw, not the recc method for using `realloc()`. – WhozCraig Aug 03 '13 at 22:33

1 Answers1

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

Lidong Guo
  • 2,817
  • 2
  • 19
  • 31