I have a simple log function that needs to print the current date and time. I’m doing it inside a function that returns a char *. When I try to set this char * into fprintf(), it doesn’t print me the string into the file: why?
Here is the function that constructs the date-time:
char * UT::CurrentDateTime()
{
char buffer [50];
time_t t = time(0); // get time now
struct tm * now = localtime( & t );
int n=sprintf(buffer, "%d:%d:%d %d:%d:%d:", (now->tm_year + 1900),
(now->tm_mon + 1), now->tm_mday, now->tm_hour, now->tm_min,
now->tm_sec);
return buffer;
}
Here is the log:
const char *time =__TIME__; // compilation time
char *currentTime = UT::CurrentDateTime(); // it's a static method; also tried to set it to const
fprintf(fp, "%s %s %s %s %s %d %s\n", __TIME__, pType, __DATE__,
currentTime, pFileName, lineNo, pMsg.c_str());
fflush(fp);
Every thing is printed except the date/time char *.
Why?
You’ve returned a pointer to a memory buffer that dies immediately. Any function that uses the pointer returned from
CurrentDateTime()is relying upon garbage.Your compiler should have warned you about this. Disregard your compiler warnings at your own peril.
Instead, either allocate this via
char *buffer = malloc(50 * sizeof char);or use C++’s memory allocation mechanisms to allocate memory that can live longer than the time the function is ‘live’ and running.