1 2 3 4 5 6 7 8 9 10
| tabMot[k]=calloc(TAILLE_MAX,sizeof(char));
if (tabMot[k]==NULL)
{
fprintf(stderr, "Erreur calloc\n");
exit(1);
}
strcpy(tabMot[k],chaine);
k++; // !!!!!!!
printf("%s\n",chaine);
printf("%s\n",tabMot[k]); //segfault |
Tu alloues à l'indice k, tu copies, tu incrémentes k et tu essayes d'accéder à un pointeur non alloué…
D'ailleurs chez moi, voilà ce qui se passe quand j'appelle ta fonction :
$ gccw test.c && ./a.out test.c: In function 'main':
test.c:35:14: warning: 'fichier' is used uninitialized in this function [-Wuninitialized]
frequenceMot(fichier);
^
bonjour
(null)
developpez
(null)
.com
(null)
$ cat rep.txt bonjour
developpez
.com
Je ne sais pas ce que ca affiche chez toi, mais tu devais voir quelque chose de louche, non ?
Quand tu veux afficher des chaines comme ça, il ne faut pas hésiter à mettre des marques plus clairs. Exemple :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| void frequenceMot(FILE *f){
f=fopen("rep.txt","r");
char chaine[TAILLE_MAX]="";
char* tabMot[TAILLE_MAX]={""};
if(f != NULL)
{
int k=0;
while (fgets(chaine, TAILLE_MAX, f) != NULL) // On lit le fichier tant qu'on ne reçoit pas d'erreur (NULL)
{
tabMot[k]=calloc(TAILLE_MAX,sizeof(char));
if (tabMot[k]==NULL)
{
fprintf(stderr, "Erreur calloc\n");
exit(1);
}
strcpy(tabMot[k],chaine);
printf("Lu {%s}\nSauve [%s]\n\n",chaine, tabMot[k]); // nouvelle façon
k++; // correction
}
}
} |
Ce qui donne :
gccw test.c && ./a.out test.c: In function 'main':
test.c:34:14: warning: 'fichier' is used uninitialized in this function [-Wuninitialized]
frequenceMot(fichier);
^
Lu {bonjour
}
Sauve [bonjour
]
Lu {developpez
}
Sauve [developpez
]
Lu {.com
}
Sauve [.com
]
Partager