user3258515
user3258515

Reputation: 75

error using struct in reading from a text file

I am a beginner in C programming and trying to use struct to store the related variables and later use them in the main program. However, when I run the same program without using struct, its running fine.

The code is presented below, which doesn't show any compilation errors but no output except segmentation fault.

#include<stdio.h>

struct test
{
char string1[10000];
char string2[10000];
char string3[10000];
char string4[10000];
}parts;

int main()
{
FILE *int_file;
struct test parts[100000];

int_file=fopen("intact_test.txt", "r");

if(int_file == NULL)
{
    perror("Error while opening the file.\n");
}
else
{
    while(fscanf(int_file,"%[^\t]\t%[^\t]\t%[^\t]\t%[^\n]",parts->string1,parts->string2,parts->string3,parts->string4) == 4)
    {
        printf ("%s\n",parts->string3);
    }
}

fclose(int_file);

return 0;
}

The input file "intact_test.txt" has the following line: AAAA\tBBBB\tCCCC\tDDDD\n

Upvotes: 0

Views: 62

Answers (2)

simonc
simonc

Reputation: 42165

Each instance of struct test is 40k so

struct test parts[100000];

is trying to allocate 4GB on the stack. This will fail, leading to your seg fault.

You should try to reduce the size of each struct test instance, give parts fewer elements and move it off the stack. You can do this last point most easily by giving it static storage duration

static struct test parts[SMALLER_VALUE];

Upvotes: 2

DiJuMx
DiJuMx

Reputation: 524

A single struct takes up 40,000 bytes, and you have 100,000 of these. That comes to 4,000,000,000 bytes, or about 4GB. I'm not surprised you are seg faulting

Please rethink what you are doing. Are you seriously trying to read in 4 strings of 10,000 characters each?

Upvotes: 0

Related Questions