自定义Shell提示符时间显示异常:输入后格式错乱重复
解决Shell提示符时间错乱及重复输出问题
问题根源
- 内存泄漏:
timef()每次调用都会通过malloc分配内存,但主循环里从未释放这些内存。内存耗尽后,malloc返回无效指针,导致后续生成的时间字符串乱码。 - 输入缓冲区残留换行符:
scanf("%c", &letra)只读取单个字符,用户输入后按回车的\n会留在缓冲区,下一次循环scanf直接读取这个换行符,触发多余的循环迭代,造成重复输出。
修复方案
1. 释放内存
主循环中先保存timef()返回的字符串,使用完毕后调用free释放,避免内存泄漏导致的无效指针。
2. 处理输入空白字符
把scanf的格式改为" %c"(注意开头的空格),自动跳过缓冲区中的空白字符(换行、空格等),确保每次读取的都是用户输入的有效字符。
修复后的代码
timef函数(逻辑不变)
char * timef() { int tempo; tempo = syscall(201) % 86400; int hora = (tempo / 3600) - 3; int minutos = (tempo / 60) % 60; int segundos = tempo % 60; char *str = malloc(9); str[0] = hora/10 + '0'; str[1] = hora%10 + '0'; str[2] = ':'; str[3] = minutos/10 + '0'; str[4] = minutos%10 + '0'; str[5] = ':'; str[6] = segundos/10 + '0'; str[7] = segundos%10 + '0'; str[8] = '\0'; return str; }
主循环(修改后)
int flag = 1; while (flag == 1){ char *time_str = timef(); printf("%s: ", time_str); free(time_str); char letra; scanf(" %c", &letra); if (letra == 'q') flag = 0; }
额外优化
- 时区处理:硬编码
-3的时区偏移不够灵活,建议用localtime等系统函数获取本地时间,避免固定偏移带来的问题。 - 错误检查:在
timef()中添加malloc的返回值校验,防止内存分配失败导致崩溃:
char *str = malloc(9); if (!str) { perror("malloc failed"); return NULL; }
内容的提问来源于stack exchange,提问作者johnmantovani
相关产品推荐
相关产品推荐

