[英]Segmentation fault for c program
我在这里的代码分段错误。
gdb:
Program received signal SIGSEGV, Segmentation fault.
_IO_fgets (buf=0x601080 <rc> "", n=100, fp=0x0) at iofgets.c:50
50 iofgets.c: No such file or directory.
码:
#include <unistd.h>
#include <stdio.h>
char rc[100];
FILE *fp;
int status;
void main() {
fp = popen("sudo lshw |", "grep UUID");
if (fp == NULL)
printf("NULL pointer");
while (fgets(rc, 100, fp) != '\0')
printf("%s", rc);
status = pclose(fp);
if (status == -1) {
printf("pclose error");
/* Error reported by pclose() */
} else{
printf("Unknown error");
}
//return 0;
}
我猜是空指针吗? 我尝试了给出的解决方案,但是没有用。 我猜是某种愚蠢的错误
抱歉,shell命令将使用sudo dmidecode | grep UUID
sudo dmidecode | grep UUID
这是错的
fp = popen("sudo lshw |", "grep UUID");
也许你的意思是,阅读popen()
fp = popen("sudo lshw | grep UUID", "r");
调用失败,但是即使您检查了fp == NULL
,您仍然继续导致未定义的行为,并导致分段错误, fp == NULL
检查仍需要中止程序,就像这样
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main() {
char rc[100];
FILE *fp;
int status;
fp = popen("sudo lshw | grep UUID", "r");
if (fp == NULL)
{
printf("error:%d: %s", errno, strerror(errno));
return -1;
}
while (fgets(rc, 100, fp) != NULL)
printf("%s", rc);
status = pclose(fp);
if (status == -1) {
printf("error:%d: %s", errno, strerror(errno));
} else { /* this means no error happened */
printf("success: pipe, closed.");
}
return 0;
}
请注意, main()
应该返回一个int
,并且正如Joachim Pileborg所评论的那样, fgets(...) == '\\0'
是错误的, fgets()
在出错时返回NULL
并且NULL == '\\0'
不一定为true 。
同样, pclose()
在错误时返回-1
,如果不返回-1
则一切按预期进行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.