'Address 0x is 0 bytes after a block of size allocated valgrind

I saw that there are many topics about it but I still struggle to understand where is my specific problem at the code..

   Node*first_word = get_first_random_node (LinkedList);
  unsigned int num_of_bytes = strlen (first_word->data) + 1;
  char *twit = malloc (num_of_bytes);
  *twit = '\0';
  strcat (twit, first_word->data);
  strcat (twit, " ");

the get_first_random_node is a legit function. It is allways return a node that his data is a string with len > 0. Yet, I keep getting that error..



Solution 1:[1]

Transferring comment into an answer.

You allocated enough space for the string data plus the null byte that ends the string; you didn't allocate enough space to add a blank at the end. You need to allocate:

size_t num_of_bytes = strlen(first_word->data) + sizeof(" ");

The sizeof() is a way of writing 2; when applied to a string literal, sizeof() counts the null byte.

Side comment: using a macro ONE for 1 is modestly silly (and changing it to #define ONE 2 so the length is right would be even sillier, but funnier things have been seen in other people's code). Literals 0 and 1 can usually be used without needing an explanation. Yes, it's important to avoid 'magic numbers' in code, but 0 and 1 are very mundane and non-magical.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jonathan Leffler