简体   繁体   中英

Segmentation faul even with memory allocation of 2d array

I'm trying to read a file that contains a five letter word on each line for 12972 lines. I'm not sure why I'm getting this error even with freeing storage.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE *file;
    file = fopen("words.txt", "r");                                                  // Opens file

    char** gssArr = (char**)malloc(12972 * sizeof(char*));       // Allocates memory for 2d array

    for(int i = 0; i < 12972; i++)
    {
        gssArr[i] = (char*)malloc(5 * sizeof(char));
    }

    char word[6];                                    // Current word being looked at from file
    int current = 0;                                    // Used for indexing x coordinate of 2d array
    while(fgets(word,6,file) != NULL)   // Not at end of file
    {
        if(word[0] != '\n')                  // Not at end of line
        {
            for(int j = 0; j < 5; j++)           // Loops through all 5 letters in word, adding them to gssArr
            {
                gssArr[current][j] = word[j];
            }
        }
        current++;                                  // Index increase by 1
    }
    fclose(file);                         // Close file, free memory
    free(gssArr);

FYI - your reader loop - you may want to make sure that your current index is not going beyond 12971.

Your problem is here:

current++; 

Why?

Because it's done even when you are at the end of the line. One solution is to move it inside the if statement but instead I'll recommend that you use fgets with a much larger buffer.

Details

If every line holds a five letter word then

fgets(word,6,file)

will read the five letters and zero terminate it. Then the next fgets will just read the "newline". Still you increment the index counter and in the end, you write outside allocated memory.

Try

while(fgets(word,6,file) != NULL)   // Not at end of file
{
    printf("current=%d\n", current);

and you see the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM