简体   繁体   中英

core dumped when i use fscanf

I tried to read a text file with the function fscanf , but everytime I get a "core dumped". It's weird because when I use another file that I already use somewhere else, the code doesn't work too and I found no syntax errors.

my function code :

 inst_def_t* lect_dico_int(char* nomFichierDico, int* p_nb_inst) {
  /*Charge le ficheier dictionnaire nomFichierDico*/
  /*Retourne un pointeur sur le tableau dictionnaire*/
  /*Stocke le nb d'instructions dans *p_nb_inst*/

int i;
char s1[512];
inst_def_t *tab;
FILE* f1=open(nomFichierDico,"r");
printf("step 1 \n");
if(f1==NULL)
      return NULL;
    }
printf("step 2 \n");
fscanf(f1,"%d", p_nb_inst);
printf("step 3 \n");
  fclose(f1);
  return tab; /* here i just want to have my fscaf working not really matter of tab value */
}

my main code :

int main()
{ 
  int NbDefInstructions = 0 ;
  inst_def_t* = lect_dico_int("tests/DICO_INSTRUCTION.txt",&NbDefInstructions);
return EXIT_SUCCESS;
}

the structure :

typedef struct {char * symbole; char type; int nb_op ;} inst_def_t;

and here my .txt :

4
ADD R 3
ADDI I 2
MULT R 2
DIV R 2

When i use my code i get to "step 2" but when it arrives to the function fscanf I got a segmentation fault (core dumped). I just want to know where is my error, that prevent me to use the function fscanf .

You're overrunning an allocated memory buffer:

char* path2=strdup("tests/");
strcat(path,"DICO_INSTRUCTION.txt");

The strdup function allocates just enough space for the given string. When you then use strcat to append to that string, you're writing past the bounds of the memory that was allocated. Doing so invokes undefined behavior , which in this case manifests as a core dump.

Either pass the full string to strdup :

char* path=strdup("tests/DICO_INSTRUCTION.txt");

Or, if the second string is not constant, or use asprintf to create a string and allocate space for it:

char *filename = "DICO_INSTRUCTION.txt";
char *path;
asprintf(&path, "tests/%s", filename);

Your other problem is here:

FILE* f1=open(nomFichierDico,"r");

You're calling open , which returns a numerical file descriptor, instead of fopen , which returns a pointer to a FILE object. You want:

FILE* f1=fopen(nomFichierDico,"r");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM