首页 > 解决方案 > C 中 asctime() 产生的字符串缓冲区溢出

问题描述

我想用 C 打印出时间asctime(),但是当文本打印出来时,随机字符会附加在timeString. 此外,syslog()日志文件中打印的文本与 shell 中打印的文本不同printf()。在代码下,我提供了两个输出的确切输出。我该如何摆脱这种行为?代码在 RaspberryPi 上运行,我通过默认的 macOS 终端登录。

  time_t rawTime;
  time(&rawTime);
  struct tm timeInfo = *gmtime(&rawTime);

  // ...

  char *log;
  char *timeString = strdup(asctime(&timeInfo));

  asprintf(&log, "UTC: %s %.*s Last status: %s. New status: %s.", 
           timeString, 5, "     ", "Hello", "World");

  openlog("httpd-status-notifier", LOG_PID, LOG_USER);
  syslog(logLevel, "%s", log);

  printf("%s\n", log);

  // ...

系统日志:

Dec 22 17:18:17 rasp httpd-status-notifier[25458]: UTC: Sun Dec 22 17:18:17 2019#012 Last status: Hello. New status: World.

(这里syslog产生#012


外壳(printf)

UTC: Sun Dec 22 17:18:17 2019 Last status: Hello. New status: World.

(这里printf产生一个新的行字符)


顺便说一句,是的,我确实注意到syslog已经记录了日期。

标签: cbufferoverflowbuffer-overflow

解决方案


The problem is that asctime() produces a new line character and this gets represented as the octal ASCII value 012 in the log file as pointed out by @mangusta in the comment section. So trimming the string solves the problem.


推荐阅读