int main(){ char temp[50], voltage[50], offset[50], wr1_linkt[50], wr1_loop[50], wr1_onew[50], wr0_linkt[50], wr0_loop[50], wr0_onew[50], time[50]; char buffer[1024]; int counter = 0; while(1){ FILE *fp = popen("/usr/bin/sn_core.elf getstat 2>/dev/null","r"); if(fp == NULL){ printf("Failed to run\n"); exit(0); } fgets(buffer,sizeof(buffer),fp); pclose(fp); char *p = strstr(buffer,"mu:"); sscanf(p,"%*[^0123456789]%[^ ]",wr1_loop); printf("%s\n",wr1_loop); p = strstr(buffer,"dms:"); sscanf(p,"%*[^0123456789]%[^ ]",wr1_onew); p = strstr(buffer,"crtt:"); sscanf(p,"%*[^0123456789]%[^ ]",wr1_linkt); p = strstr(buffer,"temp:"); sscanf(p,"%*[^0123456789]%[^ ]",temp); p = strstr(buffer,"Time:"); sscanf(p,"%*[^0-9+-]%[^.]",time); sleep(1); } return 0; } 执行该代码有Segmentation fault错误
时间: 2024-03-01 20:55:13 浏览: 134
这段代码中的 `sscanf` 函数可能会出现越界访问的情况,导致程序崩溃。具体来说,`sscanf` 函数的第二个参数可能会导致越界访问,例如 `sscanf(p,"%*[^0123456789]%[^ ]",wr1_loop);` 这一行代码中的 `%[^ ]`,它表示以空格为分隔符读取字符串,但是如果字符串中没有空格,`sscanf` 函数就会一直读取到字符串结尾,可能会导致越界访问。同样的问题还存在于其他几行代码中。
为了解决这个问题,可以将 `sscanf` 函数的第二个参数中的格式字符串改为 `%49s`,表示最多读取 49 个字符,避免越界访问。同时,还需要注意对获取的字符串进行有效性检查,避免非法字符串导致程序崩溃。
修改后的代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define MAX_BUF_SIZE 1024
int main() {
char temp[50], voltage[50], offset[50], wr1_linkt[50], wr1_loop[50], wr1_onew[50], wr0_linkt[50], wr0_loop[50], wr0_onew[50], time[50];
char buffer[MAX_BUF_SIZE];
int counter = 0;
while(1) {
FILE *fp = popen("/usr/bin/sn_core.elf getstat 2>/dev/null", "r");
if (fp == NULL) {
printf("Failed to run\n");
exit(EXIT_FAILURE);
}
fgets(buffer, sizeof(buffer), fp);
pclose(fp);
char *p = strstr(buffer, "mu:");
if (p) {
sscanf(p, "%*[^0123456789]%49s", wr1_loop);
printf("%s\n", wr1_loop);
}
p = strstr(buffer, "dms:");
if (p) {
sscanf(p, "%*[^0123456789]%49s", wr1_onew);
}
p = strstr(buffer, "crtt:");
if (p) {
sscanf(p, "%*[^0123456789]%49s", wr1_linkt);
}
p = strstr(buffer, "temp:");
if (p) {
sscanf(p, "%*[^0123456789]%49s", temp);
}
p = strstr(buffer, "Time:");
if (p) {
sscanf(p, "%*[^0-9+-]%49s", time);
}
sleep(1);
}
return 0;
}
```
这样修改后,程序应该能够正常运行了。
阅读全文