I have a function in which I need to implement the use of free () to free the memory that was used. My code is written this way:
void totalDePaisesVisitados(ALUMNO* array, int nu_Alumnos){
int ArrayLenght = 0;
int MaxPises = 70;
int lastIndex = 0;
char** stringAr = (char**) malloc(sizeof(char*)*MaxPises);
for (int i = 0; i < MaxPises; i++) {
stringAr[i] = (char*) malloc(sizeof(char)*50);
}
for (int a = 0; a < nu_Alumnos; a++) {
int numberPaises = array[a].pais->n_pais;
//printf("%s %d\n","numero de paises", numberPaises);
for (int b = 0; b < numberPaises; b++) {
int enArreglo = 0;
for (int c = 0; c < ArrayLenght+1; c++) {
//printf("%s %s %s %s\n","Comparando: ",array[a].pais->nombre[b],"con: ",stringAr[c]);
if (strcmp(array[a].pais->nombre[b],stringAr[c]) == 0) {
enArreglo = 1;
//printf("%s\n","Encontrado en el arreglo" );
}
}
if (enArreglo == 0) {
//printf("%s\n","ENCONTRADO PAIS DISTINTO" );
stringAr[lastIndex] = array[a].pais->nombre[b];
ArrayLenght++;
lastIndex++;
}
}
}
printf("%s\n","#3");
printf("%s %d\n","Numero de Paises visitados:",lastIndex);
for (int i = 0; i < MaxPises; i++) {
free(stringAr[i]);
}
free(stringAr);
}
The problem with this is that if I release the memory, an error appears:
malloc: *** error for object 0x7fe4356005d0: pointer being freed was not allocated
What is the correct way to release the memory in this function?