C/C++ Arena

Step 8 of 9

Who owns what

C has no garbage collector, so every heap pointer needs an owner: the one piece of code responsible for freeing it. Professional C code writes this down in a comment next to each function:

/* Returns a new array of new strings. The caller owns both:
   free each word, then the array, or call free_words(). */
char **split_words(const char *s, int *count);

A function that allocates something nested usually ships a matching "free" function, so callers can't get the order wrong.

Your turn: write split_words. It splits s on single spaces into separately allocated strings, stores how many in *count, and returns the array. Then write free_words. You can assume words are separated by exactly one space and s has no leading or trailing spaces. An empty string has 0 words (you may return NULL then).

Previous: A 2D grid on the heap Next: Challenge: a string builder