0

This code give back a segmentatin fault when I try to run it Nothing appears wihle building the file with gcc

If you have any Idea about where to search to fix it give your advise thanks.

necessarly its in the function readrep() that must happen,especialy with opendir() and readdir() but I don't see something wrong, thanks to help

#include<dirent.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<limits.h>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#define MAX 256


FILE* f;

void gowrite(char * chemin){
  f=fopen("locate.db.tmp","a+");

 int size=strlen(chemin);
    char str[MAX];

    fwrite(&size,sizeof(int),1,f);
    fwrite(str,sizeof(char),size,f);
    fclose(f);
}
void readRep(char* str){
  struct dirent repStruct;
  struct dirent * prepStruct;
  struct stat structStat;
  struct stat *buff;
  buff=&structStat;
  prepStruct=&repStruct;
DIR * d=opendir(str);

  while((prepStruct=readdir(d))!=NULL){

  int x;
  char* fi=malloc(sizeof(char)*MAX);
  fi=(prepStruct->d_name);
  x=stat(fi,buff);
  mode_t m;
  m=structStat.st_mode;
 int test;
 test=S_ISREG(m);

 if(test==0){

strcat(str,"/");
 strcat(str,fi);
 readRep(str);
 }
 else{
 char *chemin=realpath(fi,NULL); 
gowrite(chemin);
 free(chemin);
 chemin=NULL;
 }

 }


}

int main(int argN,char** argv){






  char* path=getenv("HOME");  
  chdir(path);

  readRep(".");









rename("locate.db.tmp","locate.db");
exit(0);





}

If you may help me thanks

  • 2
    Compile with symbols (option `-g`), then run the code using a debugger (gdb). It'll show the exact location where the crash occurs and allows ou to inspect all variables used. – alk Apr 22 '14 at 09:12
  • 3
    Also properly formatting sources whould surely raise acceptance to read them. – alk Apr 22 '14 at 09:17
  • 1
    ALWAYS check the result of fopen(). – Peter Miehle Apr 22 '14 at 09:19

3 Answers3

3

It may not be the only problem, but you are passing to readRep function the string literal "." and then within this function you use strcat to append something to it. You cannot modify string literals, and for sure you cannot append anything to them.

Wojtek Surowka
  • 20,535
  • 4
  • 44
  • 51
0
void gowrite(char * chemin){
  f=fopen("locate.db.tmp","a+");
  int size=strlen(chemin);
  char str[MAX];

  fwrite(&size,sizeof(int),1,f);
  fwrite(str,sizeof(char),size,f);
  fclose(f);

"chemin"/"size" and "str"/"MAX" do have nothing in common, not even the sizes. But you use one to output the other. ugly

btw: you do not initialize "str", so it may contain garbage.

Peter Miehle
  • 5,984
  • 2
  • 38
  • 55
0

I think I found , the readdir() function read all the current direcory and subdirectory,... (I thought it only read the current directory)

So when I make the recursive call upon my function readRep() ,that's not clear but that's may go at to much complexity to be handle .