0

I seen that there are many topics about it but I couldnt see(or understand) something that will be helpful for me. I am trying to create a function that get int max_length and then generate a random words until its generate max_length words. Then I want to print it. This is just an example when max_length is 20 and the new_word is always 'abc', but from some reason after max_length = 7 its keep giving me this error 'realloc invalid next size'..

  int num_of_words = 0;
  int max_length = 20;
  char *new_word = "abc";
  char *twit = malloc (strlen (new_word)+1);
  while (num_of_words < max_length){
    twit = realloc (twit, strlen(new_word)+5);
    strcat (twit, new_word);
    strcat (twit, " ");
    num_of_words++;
  }
  printf("%s", twit);
  return EXIT_SUCCESS;
}
OmerC
  • 29
  • 3
  • 2
    Hm. My documentation for [`realloc`](https://en.cppreference.com/w/c/memory/realloc) says that the second parameter is the _new total_ amount of bytes, not an additional amount. – M Oehm Apr 13 '22 at 15:47
  • @SupportUkraine Thank you! its wokred:). Why did you said its uninitialized? The line with the malloc considered as initilize, or am I wrong? – OmerC Apr 13 '22 at 15:55
  • @SupportUkraine Ohh why I need to add this? I mean whats it does/? – OmerC Apr 13 '22 at 15:56
  • The `malloc` call allocates the memory but *doesn't* set the values of the bytes ... to anything. – Adrian Mole Apr 13 '22 at 15:57
  • @AdrianMole so should I just use calloc and set them to 0? Does it really matter if I set the bytes immediatly after that? – OmerC Apr 13 '22 at 16:00
  • Just set the first byte to zero, or `strcpy(twit, "");` between the `malloc` and the `for` loop. – Adrian Mole Apr 13 '22 at 16:01
  • OmerC, One allocation of `(max_length + 1)*num_of_words` is enough. `realloc()` once afterward if desired. – chux - Reinstate Monica Apr 13 '22 at 16:09
  • @SupportUkraine As the words are to be randomly generated, their sum size is not known ahead of time. A final `realloc()`, though not necessary is useful to right-size the resultant string. – chux - Reinstate Monica Apr 13 '22 at 16:15
  • You should also check the return value of `malloc` and use a temp pointer with `realloc` to [use it properly](https://stackoverflow.com/questions/21006707/proper-usage-of-realloc) – yano Apr 13 '22 at 16:17
  • @SupportUkraine I'd expect `max_length` to be the _maximum length_ of a random generated word in OP's true code. – chux - Reinstate Monica Apr 13 '22 at 18:21
  • @SupportUkraine Fair enough. – chux - Reinstate Monica Apr 13 '22 at 21:33

0 Answers0