[This is more of a comment than an answer — abacabadabacaba has already posted the answer — but I hope it will clarify things a bit.]
I would argue that the memory leak is in this statement:
str_replace
internally calls malloc to get space for the new string […]
[emphasis mine] Memory management is such a fundamental concern in C that if a function allocates memory that it itself doesn't de-allocate, then that is a major property of the function, and one that needs to be documented up-front, together with information about what the caller is supposed to do about it. It should not be considered "internal" to the function, and you shouldn't have the read the entirety of the function's source-code in order to determine it. It's enough to make me suspicious of the rest of the function (and indeed, a quick glance at that function is enough to notice a lot of issues: its parameter-types should be const char *
rather than char *
; it should check the return-value of malloc
; it could be made more efficient by keeping track of the tail of new_subject
, or cleaner by using strcat
, instead of the current worst-of-both-worlds; etc.).
You didn't write str_replace
originally, but you can modify your own version, so you should change its documentation from this:
Search and replace a string with another string , in a string
to something like this:
Creates and returns a copy of subject
, but with all occurrences of the substring search
replaced by replace
. The returned string is newly allocated using malloc
; the caller should use free
.
(Your color_tags
function will need similar documentation, since it too returns a newly-allocated string using malloc
.)
That documentation in hand, there's a clear chain of "ownership": the caller of str_replace
takes ownership of the string it returns. So color_tags
has to call free
for every string returned by str_replace
, except the string that color_tags
itself will return (which in turn will be "owned" by the caller of color_tags
). Hence abacabadabacaba's answer.