Another way is to use the global char [whatever] buffer: no need to allocate (), no need free (). The color () functions always return this buffer. The only problem, which may not be the problem, is that color () will not be re-selected and should only be called once for each statement.
char g_color_buf[200]; char* color(const char* clr, char* str) { sprintf(g_color_buf, "%s%s%s", clr, str, CLR_RESET); return g_golor_buf; }
UPDATE : from the comment below, it is even better to declare g_color_buf [] as static
inside the function itself, rather than polluting the global namespace. This does not cure other problems, but, in any case, better.
As stated above, this procedure cannot be used in expressions such as:
printf("%s %s", color(CL_WHITE, "Result:"), color(CL_RED, "Error"));
because the second call to color () will destroy the work done by the first call.
Finally, in order to answer your question (necessary, because otherwise someone might say "you did not answer"), the memory highlighted in color () in your code example will remain there until you (no one else) release It. Given the average, normal use that you apparently want, it would be inconvenient to write many times:
tmp = color(CL_RED, "hello"); printf("%s", tmp); free(tmp);
The decision to use the global buffer for transmission by color () and, possibly, is accompanied by its size, for example:
printf("%s", color(buffer1, CL_RED, "Hello")); --or-- printf("%s", color(buffer2, sizeof(buffer2), CL_RED, "HelloHello"));
certainly the most correct, but boring. Well, it's not boring if you want to dial!