3

I have a problem with my log function, I tried to create a log method, which prints the current time in brackets before, but it don't work. Every time null is printed instead of the string.

This is my log function:

void log(char *szDebugString)
{
    printf("%s", szDebugString); //only for debug

    time_t currentTime;

    time(&currentTime);

    printf("%s", szDebugString); //only for debug
    printf("[%d] %s\n", currentTime, szDebugString);
}

Now when i'm calling the function:

log("test\n");

I get the following output on the console(time variies):

test
test
[1414078074] (null)

So my question is, why the string in the third printf is null?

Last test

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
NFoerster
  • 386
  • 2
  • 16

2 Answers2

3

The type of time_t is unspecified and it not always int in a test I just did it is actually long, and clang gives me this warning (see it live):

warning: format specifies type 'int' but the argument has type 'time_t' (aka 'long') [-Wformat]
printf("[%d] %s\n", currentTime, szDebugString);
         ~~         ^~~~~~~~~~~
         %ld

Passing an invalid specifier to printf is undefined behavior, possibly printf is using the extra bytes from currentTime when processing the %s format specifier.

As Keith Thompson points out there is no format specifier for time_t but you can convert it to a known type such as long:

printf("[%ld] %s\n", (long)currentTime, szDebugString);
         ^^^         ^^^^^^

Note, that log is used in the standard library and you should not be using that name.

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
1

The below link might help you:

What is ultimately a time_t typedef to?

Since the time_t doesn't specify any particular type or range this will lead to undefined behavior.

You also need to change your function name because compiler may throw below warning:

warning: conflicting types for built-in function 'log'
Community
  • 1
  • 1
Gopi
  • 19,784
  • 4
  • 24
  • 36