C 赛格。不知道为什么

C 赛格。不知道为什么,c,readdir,opendir,C,Readdir,Opendir,我不知道为什么我会出现seg故障。我知道它在我的pidspec函数中的某个地方,但我不确定为什么会发生这种情况。该程序的目标是将进程id作为第一个参数传递给程序,从那里,pid位于proc文件夹中,该文件的内容显示到控制台。任何帮助都将不胜感激。我已经有一年没有写C了,所以我有点生疏了 #include <stdio.h> #include <sys/types.h> #include <dirent.h> #include <errno.h>

我不知道为什么我会出现seg故障。我知道它在我的pidspec函数中的某个地方,但我不确定为什么会发生这种情况。该程序的目标是将进程id作为第一个参数传递给程序,从那里,pid位于proc文件夹中,该文件的内容显示到控制台。任何帮助都将不胜感激。我已经有一年没有写C了,所以我有点生疏了

#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h> 
#include <string.h>


void pidspec(char *v){
        DIR *myDirectory;
        struct dirent *myFile;
        char *proc = "/proc";
        printf("Made it here");
        myDirectory = opendir(proc);
        if(myDirectory){
                printf("Made it here");
                if(strcmp(myFile->d_name, v) == 0){
                        myDirectory = opendir(v);
                        if(myDirectory){
                                while ((myFile = readdir(myDirectory)))
                                        printf("%s\n", myFile->d_name);
                        }

                }

        }
        return;
}

int main(int argc, char  *argv[]){
        printf("Made it here");
        if(argc == 2){
                printf("%s",argv[1]);
                pidspec(argv[1]);       
        }
        return 0;

}
在第一次运行时,myFile没有初始化,也就是说没有指向任何东西,然后取消引用它

struct dirent *myFile;
...
if(strcmp(myFile->d_name, v) == 0) 

因此,要么您不是有意在这里使用myFile,要么确保它首先指向某个对象。

分段错误?现在正是将其放入调试器并找出原因的好时机。找到故障点,然后在故障点之前一步一步地检查可能出现的问题。注意局部变量。printf调试只能完成到目前为止。您是否获得了核心文件?您可以将其与gdb之类的调试器一起使用,以确定故障点。您尝试过谷歌搜索它吗?遍历目录是一个相当标准的算法。