Home > Mobile >  Where is the error? (C program won't print out the content of dynamic array)
Where is the error? (C program won't print out the content of dynamic array)

Time:03-21

The task was to read the first 20 lines from a specific file and format them to use only specific parts, the next step was to store those formatted strings in a dynamic array (char ** str | a pointer to a pointer), send it to a function and print it out with said function

Here is the main code:

int main(int argc, char* argv[]){
    FILE* file = fopen("./passwd.txt", "r");  // open file

    if (!file)
    {
        perror("Error opening file");
        return 1;
    }
    char line [MAXCHARS];
    int counter = 0;
    char ** str;
    str = malloc(20  * sizeof (char*));
    while (fgets(line, MAXCHARS, file) && counter < 20) {
        char * position;
        if ((position = strchr(line,':'))){
            char * end_char;
            *position = 0;        //setting here the value 0, will terminate the string line (first column)
            if((position = strchr(  position,':')) && (end_char = strchr(  position,':'))){ //increment the position to skip the second column
                *end_char = 0; //set the value 0 to end_char to terminate the string pointed by position
                char * temp_str = "\0";
                sprintf(temp_str, "{%d} - {%s}\n", atoi(position), line ); //concatenate line and userID into one string and store it into a temporary string
                *(str   counter) = malloc(sizeof (char) * strlen(temp_str)); //set the memory space for the temp_string into the array
                *(str   counter) =  temp_str; //copy the string into the array

            }
        }
        counter  ;
    }

    printArray(str);

    fclose(file);
    if (line)
        free(line);


    return 0;
}

And here is the print function:

void printArray(char ** array){
    for(int i = 0; i < 20; i  ){
        printf("%s",*(array i));
        free(*(array i));
    }
    free(array);
}

I cannot find the error, the code compiles with

Process finished with exit code -1073741819 (0xC0000005)

So at least it compiles, and I think is just a problem in my pointers handling skills, but I'm not able to find the error.

Can someone help me?

CodePudding user response:

there are 3 errors in your program :

  1. use temp_str which haven't allocated.

    char * temp_str = "\0";
    sprintf(temp_str, "{%d} - {%s}\n", atoi(position), line ); 
    
  2. save temp_str local pointer's address to str counter and use the pointer after it went out of scope at printArray=> undefined behavior

  3. line is not a pointer, can't use free

    if (line)
    {
       free(line);
    }
    

lets try this. https://godbolt.org/z/7KPfnTEMY I correct these points

  • Related