0

I am currently trying to read in two strings s and t that will be input to stdio. They will be input on separate lines.

The following code segfaults.

#include <stdio.h>
#include <string.h>
#include <math.h>

int main()
{
    char t[5000000];
    char s[5000000];

    fgets(t,50000,stdin);
    fgets(s,50000,stdin);

    printf("%c",t[1]);


}

However, a single fgets doesn't.

#include <stdio.h>
#include <string.h>
#include <math.h>

int main()
{
    char t[5000000];
    char s[5000000];

    fgets(t,50000,stdin);

    printf("%c",t[1]);

}

Other posts talk about some return and "/n" issues, but I don't understand what the problem is exactly.

Essam
  • 157
  • 1
  • 2
  • 12

2 Answers2

0

The arrays are too big to declare them on the stack, it fills up and a Stack Overflow occurs, either declare them on the heap with malloc or make them smaller.

Declaring them static will also make it work as static variables are stored in a different place in memory not on the stack.

Alex Díaz
  • 2,303
  • 15
  • 24
0

FYI :

Stack size varies according to platform, on linux platform stack size is by default 8MB. You can varify it and also change it according to your need using system calls getrlimit() and setrlimit().

Chintan Patel
  • 310
  • 1
  • 2
  • 11