2

I am having a weird issue with this C program I'm writing to loop through a directory and open each file to do some work on. My program is located in the parent directory of the directory I'm searching through. In order for fopen to be able to see the files in that directory I am making a chdir(path) call right before my while((dp = readdir(dfd)) != NULL) call. The first file gets picked up fine but I get a segfault for the next iteration on this call. It seems to be a problem with the chdir and readdir logic and I'm not sure how to fix it. Any ideas? Here is my code:

if((dfd = opendir(dir)) == NULL){
    fprintf(stderr, "Can't open %s\n", dir);
    return 0;
}
chdir(dir);

char *filename;
//loop through the directory
while((dp = readdir(dfd)) != NULL){
    printf("Searching file %s\n", dp->d_name);
    filename = malloc(50);
    filename = dp->d_name;
    char text[80];
    int words = 0;
    int cellular = 0, CDMA = 0, GSM = 0, LTE = 0, wireless = 0, realtime = 0, GPS = 0, remote = 0, monitor = 0;
    struct stat stbuf;

    //Skip any directories
    if((stbuf.st_mode & S_IFMT) == S_IFDIR){
      printf("Directory skipped.\n");
      continue;
    }

    //Skip files that can't be opened
    if((fpt=fopen(filename,"r")) == NULL){
      printf("Couldn't open file %s.\n", filename);
      continue;
    }

    //search the file
    while(fscanf(fpt, "%s", text) != EOF){
      words++;
      //....etc
  • I've run it through gdb, the segfault occurs on the second iteration of the while((dp = readdir(dfd)) != NULL). – user3522016 Jun 04 '15 at 22:48
  • 1
    `filename = malloc(50); filename = dp->d_name;` = memory leak in two short lines. You just threw away the memory `malloc`'d on the line before. – WhozCraig Jun 04 '15 at 22:49
  • @user3522016 my bad didn't read the question all the way through I'll remove my comment – Spidey Jun 04 '15 at 22:50

1 Answers1

2

You are most likely corrupting memory, causing succeeding calls to readdir() to fail as data in the dfd structure gets mangled. You are doing a few "bad" things in your code:

  • filename=malloc() followed by filename=... - this causes memory leak (but not the segfault)
  • fscanf(fpt,...) - you allocate 80 bytes on the stack for that, but you then are asking libc to read a "word". If the word is over 80 characters, you will corrupt anything that's on the stack. This is most likely causing the segfault. You may have further code we don't see that's doing something as bad as that.
Pawel Veselov
  • 3,527
  • 4
  • 32
  • 55