我的日志功能有问题,我尝试创建一个日志方法,该方法将当前时间打印在方括号内,但不起作用。每次打印null而不是字符串。
这是我的log
函数:
void log(char *szDebugString)
{
printf("%s", szDebugString); //only for debug
time_t currentTime;
time(¤tTime);
printf("%s", szDebugString); //only for debug
printf("[%d] %s\n", currentTime, szDebugString);
}
现在,当我调用该函数时:
log("test\n");
我在控制台上得到以下输出(随时间变化):
test
test
[1414078074] (null)
所以我的问题是,为什么第三个
printf
中的字符串为null? 最佳答案
time_t的类型是未指定的,在我刚刚做的测试中它并不总是int,实际上它很长,并且clang
给我这个警告(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
将无效的说明符传递给
printf
是undefined behavior,可能printf
在处理currentTime
格式说明符时正在使用%s
的额外字节。正如Keith Thompson指出的那样,time_t没有格式说明符,但是您可以将其转换为已知类型,例如long:
printf("[%ld] %s\n", (long)currentTime, szDebugString);
^^^ ^^^^^^
请注意,在标准库中使用了log,因此您不应使用该名称。