Hello everyone. I'm new in this forum, but I have quite some time reading in the background all the amazing help you give here.
I'm trying to write a spellchecker, and I have a dictionary file wich I want to allocate in memory so I can compare strings. The problem is, after a few iterations, glibc show the error:
*** glibc detected *** realloc(): invalid next size: 0x0804a180 ***
Here's the code I'm working on, the problem is probably the use of pointers to pointers to chars, and the realloc function... Because I increment the size of the DICC array of pointers, and then malloc a size to put a word in the DICC[cant] space that I've created with realloc... I know it's a bit confusing at first, but I don't know what the problem is exactly... I'm working with linux, by the way...
Glosary: DICC is an array of pointers to pointers of chars. Cant is the total amount of words that the program reads from the file, "archivo" is the dictionary file, and that's all...
Code:
void cargaDicc(){
FILE *archivo;
char *word = malloc(sizeof(char));
char **TEMP = NULL;
char *nombreArch;
int cant = 0;
char **DICC = NULL;
archivo=fopen(nombreArch,"r");
if(archivo==NULL) {
printf("No se pudo abrir el archivo de diccionario.\n");
}else {
while(fscanf(archivo,"%s",word) != EOF){
TEMP = realloc( DICC, cant+sizeof(char*));
if(TEMP != NULL){
DICC = TEMP;
DICC[cant] = malloc(strlen(word)+1);
strcpy(DICC[cant],word);
cant++;
}else{
printf("No se pudo realocar memoria\n");
free(DICC);
exit(1);
}
}
printf("Se han cargado satisfactoriamente %d palabras del diccionario.\n", cant);
fclose(archivo);
free(archivo);
free(word);
free(TEMP);
}
}
Every help would be apreciate...
I'm trying to eliminate memory leaks issues and nasty things like that...
Edit: By the way... If I comment the lines
Code:
DICC[cant] = malloc(strlen(word)+1);
strncpy(DICC[cant],word);
The dictionary loads completly and at the end it shows a segmentation problem (I supose because 'm not free'ing the memory of DICC yet...)