0

When I compile the following code using gcc test.c -o test and then run test, I get a Segmentation fault: 11 message:

int main(int argc, char *argv[])
{
    double xs[600000];
    double ys[600000];

    return 0;
}

What is going on? If I remove the ys declaration, then it works, and if I make the array size smaller (eg. 500000), then it works. I am stumped.

Dennis Kozevnikoff
  • 2,078
  • 3
  • 19
  • 29
Bruce Bartlett
  • 213
  • 2
  • 5
  • Because you are running out of stack space – Jim Rhodes Sep 11 '21 at 22:05
  • Ok, yes, thank you. But I am very surprised that I run out of memory so fast. A double is 8 bytes, so I'm only trying to allocate about 10Mb of memory here. Surely my modern computer can do that. I thought I had 8Gb of RAM. – Bruce Bartlett Sep 11 '21 at 22:14
  • 1
    stack is not infinite; in the linux & windows word, default stack size is 1-2 Mb You are trying to put more than 9 Mb on the stack, so the error – Gian Paolo Sep 11 '21 at 22:17
  • 1
    You are not running out of memory. `xs` and `ys` are automatic variables and therefore are allocated on the stack. You are overflowing the stack. – Jim Rhodes Sep 11 '21 at 22:18
  • 1
    @BruceBartlett, your are not running out of memory, you are running out of the memory reserved for the stack. try to allocate on the heap the same amount of bytes (`double[] xs = new double[600000]`), you will have no problem doing that – Gian Paolo Sep 11 '21 at 22:22
  • Ok thank you. One last question - if I try to debug by putting in a printf("Executed this line.\n") before the line which causes the stack overflow, then the printf actually doesn't execute. That is kind of spooky - what order are things executed in? – Bruce Bartlett Sep 11 '21 at 22:27

0 Answers0