-
char *functionName()
-
{
-
char Date6[11]=NULL;
-
time_t current,c6;
-
struct tm *tm,*now;
-
current = time(NULL);
-
c6 = current - (6 * 3600 *24);
-
now = localtime(&c6);
-
-
//printf("Date is %02d/%02d/%02d\n", now->tm_mon+1, now->tm_mday,now->tm_year+1900);
-
//printf("Time is %02d:%02d\n", now->tm_hour, now->tm_min);
-
snprintf(Date6, sizeof(Date6), "%02d/%02d/%02d", now->tm_mon+1, now->tm_mday, now->tm_year+1900);
-
return Date6;
-
}
The problem in this code is that you are returning data that resides on the stack, that is you return Date6 but Date6 is declared as a local variable of functionName. As soon as function name exits Date6 is returned to the stack.
This basically invokes undefined behaviour. Undefined behaviour is bad because once invoked your program will behave in a completely unpredictable manor. You have seen this, the function works with the printf statements in place and doesn't without them even though there is no logical reason why they should make a difference.
Never return data that is located on the stack.
You have 3 choices, the first, simple but somewhat more programming practice, is to make Date6 static (add the static keyword before it's declaration. This will then place Data6 in the global data segment and it will always exist so you wont have a problem returning it. However this method is not re-entrant and wont work on a multi-threaded system.
The second is somewhat more complex, allocate memory from the heap (using malloc) inside functionName and return that data. Because it is allocated from the heap it will continue to exist after the function exits but the calling code will have to remember to free the data once it has finished with it.
The third method is to pass a buffer (and a size of the buffer) into functionName from the calling code via a pointer and for functionName to put it's result directly into that buffer. The calling code then becomes responsible for allocating the memory (on stack, heap or globally) and freeing it if necessary once used.
Personally I would used the third method, the first method doesn't work properly except in very simple circumstances, and I do not like allocating memory in a function at a lower level for release by a function at a higher level in a different part of the code. It tends to lead to memory leaks through thoughtless programming (i.e. forgetting to do the free) so that rules out method 2.
And finally functionName is an extremely poor name for a function, the name of a function should give an idea of what it does.