I am basically trying to create a log file which has date and time as its name. This is my code
char logger [500]; time_t time1; struct tm * timeinfo; time (&time1); timeinfo = localtime (&time1); sprintf(logger, "TestTreiber_%d%d%d%d%d%d.log",timeinfo->tm_year+1900,timeinfo->tm_mon+1,timeinfo->tm_mday,timeinfo->tm_hour,timeinfo->tm_min,timeinfo->tm_sec); printf("All logging during this test is done in : %s",logger); sprintf(logger, "prot/%s",logger);//STEP 1: I encounter the error here FILE *logFile; logFile= fopen(logger,"w");
Without the step 1 every thing worked fine. It created a log file with the name I wanted in the same folder where my program is. But when I add step 1 into the mix it gives me this error.
Segmentation Fault (core dumped)
I am new to Linux but I know it has something to do with memory so I increased the memory allocated to logger[500] (it was earlier 255 which worked fine). But I can’t seem to solve this problem. prot folder does exist in the directory I am running this. Please help!
PS Sorry about wrong usage of capital letters, I am using a German Keyboard.
Advertisement
Answer
You should not do this in your code,
sprintf(logger, "prot/%s",logger);
Quoting from the man
page of sprintf,
Some programs imprudently rely on code such as the following,
sprintf(buf, "%s some further text", buf);
to append text to
buf
. However, the standards explicitly note that the results are undefined ifsource
anddestination
buffers overlap when calling sprintf(), snprintf(), vsprintf(), and vsnprintf(). Depending on the version of gcc used, and the compiler options employed, calls such as the above will not produce the expected results.