c - segmentation fault with reading from directory -


i trying read 2 directories , place contents 2 dynamic arrays when read getting seg fault. place see in loop add?

 #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <dirent.h>  int main(int argc, char** argv) {    // directory parameters      dir *dira;   dir *dirb;   struct dirent *da;   struct dirent *db;    //check if dir exists   if (!(dira = opendir(argv[1])))     fprintf(stderr,"failed open directory %s \n",argv[1]);   //check if dir b exists   if (!(dirb = opendir(argv[2])))     fprintf(stderr,"failed open directory %s \n",argv[2]);   //open dir   dira= opendir(argv[1]);   dirb= opendir(argv[2]);   int sizea;   int sizeb;    while (0!= (da = readdir(dira)))    {        sizea++;      }    while (0!= (db = readdir(dirb)))     {       sizeb++;     }   char**contentsa;   char**contentsb;   contentsa=(char**)(malloc(80*sizeof(char*)));   contentsb=(char**)(malloc(80*sizeof(char*)));   int i=0;   while (0!= (da = readdir(dira)))     {      contentsa[i]=da->d_name;       i++;     }   i=0;      while (0!= (db = readdir(dirb)))    {      contentsb[i]=db->d_name;    }      ( i=0; i<sizea; i++) {    printf("%s\n", contentsa[i]); }    ( i=0; i<sizeb; i++) {    printf("%s\n", contentsb[i]); }   printf("size = %d \n size b = %d\n", sizea, sizeb);   return (exit_success);    } 

i think problem might in last loop

there many errors.

one you're storing name pointers directory entries, not copying string data. you're copying pointer, points memory don't own. it's highly of names point same location in memory.

further, never use count of items in each directory, instead hardcode 80 entries. if there more 80 overwrite random memory.

you should close directory , re-open it, or (better) call rewinddir() before looping second time, otherwise directory stream exhausted.


Comments

Popular posts from this blog

html - Sizing a high-res image (~8MB) to display entirely in a small div (circular, diameter 100px) -

java - IntelliJ - No such instance method -

identifier - Is it possible for an html5 document to have two ids? -