I have this simple function:
char*
get_time()
{
char *buffer = malloc(sizeof(char)*10); /* HOW TO FREE IT ? */
time_t rawtime;
struct tm * timeinfo;
time(&rawtime);
timeinfo = localtime(&rawtime);
strftime(buffer,10,"%H:%M:%S",timeinfo);
return buffer;
}
The issue is with strftime()
which requires a char*
and I can't free(buffer);
before returning his content. What could I do?
The macro where I use the function:
#define log_info(msg) printf("%s [INFO ] - %s\n",get_time(), (msg))
Something like this
static char g_buffer[10];
#define log_info(msg) \
do { \
get_time(); \
printf("%s [INFO ] - %s\n", g_buffer, (msg)); \
g_buffer[0] = '\0'; \
} while (0)
static int get_time()
{
time_t rawtime;
struct tm * timeinfo;
time(&rawtime);
timeinfo = localtime(&rawtime);
strftime(g_buffer,sizeof(g_buffer),"%H:%M:%S",timeinfo);
return 0;
}
int main(void) {
log_info("test");
return 0;
}
But and don't get the need of a macro, a function will do the job