-1

I am not sure why I am getting a seg fault. I know it is somewhere in my pidspec function but I'm not sure why it is happening. The goal of this program is to have the process id passed in as first argument to program, from there, the pid is located in the proc folder and the contents of that file are displayed to console. Any help would be greatly appreciated. I haven't written any C for a year so I'm a bit rusty.

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

}
tadman
  • 208,517
  • 23
  • 234
  • 262
  • 1
    Segmentation fault? Great time to pop this into your debugger and find out why. Find the point of failure, then step through just prior to that to see what might be going wrong. Pay careful attention to local variables. `printf` debugging can only get you so far. – tadman Sep 18 '18 at 00:48
  • [Turn on compiler warnings](https://gcc.godbolt.org/z/JGMTcw). – Raymond Chen Sep 18 '18 at 00:52
  • Did you get a `core file`? You can use this with a debugger (like gdb) to determine the point of failure. – Kingsley Sep 18 '18 at 00:53
  • Did you try *Google*ing it? Traversing a dir is a a pretty standard algorithm. – CristiFati Sep 18 '18 at 00:54

1 Answers1

3

On your first run, myFile is not initialised, that is not pointing to anything, and then you de-refernece it!

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

So either you didn't mean to use myFile here, or ensure it's pointing at something first.

Kingsley
  • 14,398
  • 5
  • 31
  • 53