c - 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
已经记录了日期。
解决方案
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.
推荐阅读
- angular - 避免覆盖表组件中的注入对象
- reactjs - TypeError:无法读取 react-localize-redux 中未定义的属性“语言”
- python - 由于 EnvironmentError 无法安装 Open-CV:[WinError 5] 访问被拒绝
- javascript - 数组中的 React 映射数据驻留在一个对象中
- ios - AVAssetWriter:开始写入时的瞬间滞后
- python - 如何并行化while循环?
- c++ - 卡牌游戏程序在进行中。不知道为什么我得到一个随机数-858993460
- python - 仅遍历数组的某个部分的正确方法?
- python - 当我使用字符串时,为什么会得到“预期的字符串或缓冲区”?
- performance - 提高学生信息应用程序的性能