When I try to pass the current time as a string to the function logger in my code I get an error saying that "Segmentation fault (core dumped)". but when I put static char str[30]
the error doesn't come. but with no errors the resulting file makes impossible to open it.
void logger(char * logType, int loggingLevel, char * massage)
{
FILE *fp = fopen("log.txt", "a");
fprintf(fp, "%s|%d|%s|%s",logType,loggingLevel,massage,currentTime());
fclose(fp);
}
char * currentTime(void)
{
time_t rawtime;
char str[30];
char *string;
struct tm * timeInfo;
time(&rawtime);
timeInfo = localtime(&rawtime);
strftime(str, 26, "%Y:%m:%d %H:%M:%S", timeInfo);
return str;
}
so previously I made the currentTime function like this
char * currentTime(void) {
time_t rawtime;
struct tm * timeinfo;
time(&rawtime);
timeinfo = localtime(&rawtime);
return asctime(timeinfo);
}
it works fine but that is not the way I need to display the time.
You are returning a local variable from function currentTime()
which is undefined behaviour.
Change function signature to: char * currentTime(char *inputBuffer, size_t bufLen)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments