let's say I'm writing a function like strdup(), or any other function that uses malloc() for that matter. If I only call this function inside of printf() like this :
printf("%s", my_function(arg));
Is it possible to free the value returned from the function ? If yes, how ? To my knowledge, free() takes as argument a void pointer but how do you get that pointer if you never store de returned value in a variable ?
Is it possible to free the returned value of a function (only) called inside of printf (in c)?
No.
Alternative: "allocate" with a compound literal.
Instead of allocating in my_function(char *arg)
, determine size needed and pass the compound literal to my_function(char *arg, char *buf)
, which then returns buf
.
Instead of allocating in my_function(char *arg)
, if the maximum size is not too large, pass the compound literal to my_function(char *arg, char *buf)
, which then returns buf
.
#define MY_FUNCTION_SIZE 42
printf("%s", my_function(arg, char [MY_FUNCTION_SIZE]{0}));
The compound literal is valid until the end of the block of code. Then it is "unallocated". Neither malloc()
, free()
nor is an explicit named temporary object needed.