[Solved] Invalid read of size – C valgrind


Here after is a proposed solution in main() :

List of the corrected errors and enhancements:

1- in the formatting output, replace %p (dedicated to pointers) by %s (dedicated to strings).

2- before storing in the output string zeile_array[d] allocate it to the len of the output text zeile including the null-terminator.

3- instead of copying output text pointer zeile to the output string zeile_array[d], use the strcpy() function to move all characters.

4- to simplify, modify the temporary string zeile from char pointer dynamically allocate in the memory by a simple char array allocated automatically in the stack.

5- to protect, stop the extraction of result when all items of the array char *zeile_array[50]; have been used. Or simply allocate enough array by using the MAX_LAENGE_ARR constante.

// Hier implementieren
int x=0;
int d=0;
//int b=0;
//char* zeile_array=(char*) malloc (len * sizeof(char));
char *zeile_array[MAX_LAENGE_ARR]; // instead of char *zeile_array[50];
char zeile[100];
// zeile=(char*) malloc(100); // allocated memory not needed
for(x=0;x<len;x++)
{
    if(strcmp(laender[x],bundesland) == 0 && bewohner[x] >= anzahl)
    {
        // as Micheal Walz said, replace %p by %s
        sprintf(zeile, "Die Stadt %s hat %d Einwohner.",staedte[x],bewohner[x]);
        // allocate the storing item
        zeile_array[d]=(char *)malloc(strlen(zeile)+1);
        // copy the formatted text into the storing item
        strcpy(zeile_array[d],zeile);   // putting it into array
        d=d+1;
        // abort research when output array is full
        if (d >= MAX_LAENGE_ARR) break;
    }
}
//b++;
//} // remove unexpected end of block
write_file(zeile_array,d);
// free the allocated memory only
for(x=0;x<d;x++)
{
    free(zeile_array[x]);
}
// free(zeile); is no more needed

5

solved Invalid read of size – C valgrind