Printf output is null when combined with int C

I have a problem with my log function, I tried to create a log method that used to print the current time in brackets, but it doesn't work. Each time, zero is printed instead of a string.

This is my function log

:

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 call the function:

log("test\n");

      

I am getting the following output on the console (temporary options):

test
test
[1414078074] (null)

      

So my question is, why is the row in the third printf

null?

Last test

+3


source to share


2 answers


The time_t type is not specified and it is not always int in the test, I just did it for really long time 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

perform undefined behavior , possibly printf

consuming extra bytes from currentTime

when processing the format specifier %s

.



As Keith Thompson points out, there is no format specifier for time_t, but you can convert it to a well-known type like long:

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

      

Note that log is used in the standard library and you should not use this name.

+3


source


The following link can help you:

What is the time_t typedef for?

Since it time_t

doesn't specify any particular type or range, this will result in undefined behavior.



You also need to change the name of your function, because the compiler might throw below warning:

warning: conflicting types for built-in function 'log'

      

+1


source







All Articles