Home > front end >  Segmentation faul even with memory allocation of 2d array
Segmentation faul even with memory allocation of 2d array

Time:02-25

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);

CodePudding user response:

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

CodePudding user response:

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.

CodePudding user response:

Why do you bother doing it like this?

Creating an array of character pointers to five letter words?

First determine the size of the file with ftell,fseek

Create a buffer

Then read in the whole file into the character buffer, then go through the buffer looking for end of lines. \n

FILE *file;
file = fopen("words.txt", "rb");
fseek(file, 0L, SEEK_END);
long size = ftell(file);
fseek(fike, 0L, SEEK_SET);
char* buffer = malloc(size);
fread(file, 1, size, buffer);

now you have the whole file in memory, go through the file

  • Related