Consider the following function:
char* color(const char* clr, char* str)
{
char *output = malloc(strlen(str)+1);
/* Colorize string. */
sprintf(output, "%s%s%s", clr, str, CLR_RESET);
return output;
}
The above function allow us to print colorized messages in linux terminal.
So I can write
printf("%s", color(CLR_RED, "This is our own colorized string"));
and see the message This is our own colorized string
in red.
My concern is the output
string allocated in color()
. By the time the function returns an allocated element (array in our example) we somewhat need to deallocate it (C does not have a garbage collector).
My question is, what happens to the output
after is passed to printf()
? When we exit the function printf()
the array is still allocated? If it is, how we can deallocate it? Is there any way to write a function that do this for us?
Thanks in advance!