Search code examples
csegmentation-faultcharacter-arrays

Seg Fault char** C


I'm trying to figure out why I can't store a file into char**.

I thought I allocated memory correctly. Can someone please help me? Thank you!

Also, I know my way isn't the most efficient way to go about the problem, but first I want to get the problem done before I worry about efficiency. Thank you!

void readFile(int argc, char** argv)
{
    FILE *myFile;
    char** list;
    char c;
    int wordLine = 0, counter = 0, i;
    int maxNumberOfChars = 0, numberOfLines = 0, numberOfChars = 0;

    myFile = fopen(argv[1], "r");

    if(!myFile)
    {
        printf("No such file or directory\n");
        exit(EXIT_FAILURE);  
    }

    while((c = fgetc(myFile)) !=EOF)   //goes through the file to get # of lines
    {                                  //and columns so I can allocate array
        numberOfChars++;
        if(c == '\n')
        {
            if(maxNumberOfChars < numberOfChars)
                maxNumberOfChars = numberOfChars + 1;

            numberOfLines++;
        }
    }

    fseek(myFile, 0, SEEK_SET);   //resets file pointer

    list = malloc(sizeof(char*)*numberOfLines);  //dynamically allocating

    for(i = 0; i < wordLine ; i++)
        list[i] = malloc(sizeof(char)*maxNumberOfChars);


    while((c = fgetc(myFile)) != EOF)       //stores in words
    {
        if(c == '\n' && counter > 0)
        {
            list[wordLine][counter] = '\0';
            wordLine++;
            counter = 0;
        }
        else if(c != '\n')
        {
            list[wordLine][counter] = c;   //seg fault happens at first character
            counter++;
        }
    } 
    fclose(myFile);
}

Solution

  • At this point:

    for(i = 0; i < wordLine ; i++)
    

    wordLine = 0, so no memory will be allocated. I think it should be:

    for(i = 0; i < numberOfLines; i++)
    

    And you need to set numberOfChars = 0, similar to what Grijesh Chauhan said, otherwise you'll allocate too much memory.