简体   繁体   English

C程序分段错误

[英]Segmentation fault for c program

I got segmentation fault for the code here. 我在这里的代码分段错误。

gdb : 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.

Code: 码:

#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;
}

null pointer I guess? 我猜是空指针吗? i tried with solutions given , but not worked. 我尝试了给出的解决方案,但是没有用。 Somehow silly mistake I guess 我猜是某种愚蠢的错误

sorry , the shell command will b sudo dmidecode | grep UUID 抱歉,shell命令将使用sudo dmidecode | grep UUID sudo dmidecode | grep UUID

This is wrong 这是错的

fp = popen("sudo lshw |", "grep UUID");

maybe you mean, read popen() 也许你的意思是,阅读popen()

fp = popen("sudo lshw | grep UUID", "r");

the call failed, but even though you checked for fp == NULL , you continued anyway causing undefined behavior, and leading to the segmentation fault, the fp == NULL check needs to abort the program, like this 调用失败,但是即使您检查了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;
}

note that main() shall return an int , and as Joachim Pileborg commented, fgets(...) == '\\0' is wrong, fgets() returns NULL on error and NULL == '\\0' is not necessarily true. 请注意, main()应该返回一个int ,并且正如Joachim Pileborg所评论的那样, fgets(...) == '\\0'是错误的, fgets()在出错时返回NULL并且NULL == '\\0'不一定为true 。

Also, pclose() returns -1 on error, if it does not return -1 then everything went as expected. 同样, pclose()在错误时返回-1 ,如果不返回-1则一切按预期进行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM