When I try to read the c language file and save it to an array, Segmentation Fault appears.

Asked 2 weeks ago, Updated 2 weeks ago, 0 views

I wrote a code that reads words.dat, a file consisting of multiple lines of string using void add_words(), but when I run it on Linux, segmentation fault appears.

I have no knowledge of fopen so I am not sure why the error occurred.

Thank you.

Note:This is the content of words.dat.

aargh
abaca 2
abaci+1
aback*2,2,3
.
.
.
.
.
.
zooey
zooks
zooms*3,1
zowie 4

Below is the code.

void add_words() //words.dat is a function that receives input.
{


    charp[5762][5]; //Real final storage
    char *name;
    char test[1]; //String to test whether the first character is * or not
    int i = 0;
    FILE* fp=NULL;

    int f = 0;
    fp = fopen("words.dat", "r");
    If (fp == NULL) //Emergency Escape if the file is empty.
    {
        fprintf(stderr, "File Open Error!\n");
        exit(1);
    }

    For (i = 0; i < 5762; i++) // Read 5 lines of characters.
    {

        name = (char*)malloc(sizeof(char) * MAX);
        fgets(name, MAX, fp);


        test[0] = name[0];

        If (test[0] == '*') //if the first character is *
        {
            goto Skip;
        } Just skip it.
        else {


            for (f = 0; f < 5; f++)
            {
                p[i][f] = name[f]; // The final array is p.
            }
        }






    Skip:



        All data will be stored in array n[].

        ;

    }
    fclose(fp);
    return ;
}

c

2022-09-20 14:32

1 Answers

Please refer to the code below.

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

int main()
{
    FILE* fp = fopen("words.dat", "r");
    if (fp == NULL) {
        fputs ("File Open Error\n", stderr);
        return 1;
    }

    // Freeing up memory
    char* p_word_list[5757] = { 0 };
    for (int i = 0; i < 5757; ++i)
        p_word_list[i] = malloc(sizeof(char) * 6); // 5 characters + null character space 1 = 6

    // Read File
    for (int i = 0; i < 5757; ++i)
        fscanf(fp, "%s", p_word_list[i]);

    // Test Output
    for (int i = 0; i < 10; ++i)
        printf("%d: %s\n", i, p_word_list[i]);

    for (int i = 5747; i < 5757; ++i)
        printf("%d: %s\n", i, p_word_list[i]);

    // Memory release
    for (int i = 0; i < 5757; ++i)
        if (p_word_list[i]) free(p_word_list[i]);

    return 0;
}


2022-09-20 14:32

If you have any answers or tips


© 2022 pinfo. All rights reserved.