c程序的分段错误

时间:2015-02-17 19:04:00

标签: 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命令将为b sudo dmidecode | grep UUID

1 个答案:

答案 0 :(得分:4)

这是错误的

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,那么一切都按预期进行。