c - c程序的段错误

标签 c segmentation-fault

这里的代码出现段错误。

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

最佳答案

这是错误的

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'不一定是真的。

此外,pclose()返回 -1出错时,如果它不返回 -1然后一切都按预期进行。

关于c - c程序的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28569142/

相关文章:

c - 为什么我会在这里出现段错误

c - 从文件中读取单词并将其作为字符指针返回

c - 当我运行这个程序时结构崩溃

c - 在简单循环中获取段错误

c - 打印结构段错误数组

c++ - 使用 qsort 导致段错误

c - 递归搜索二叉树中的元素时出现问题

c - 如何从 C 中的只读 FIFO 读取一行?

c++ - volatile sig_atomic_t 的内存安全

c - 什么是程序的十六进制版本,它的用途是什么