2

So,i was solving a problem on SPOJ.I have to handle large number of values of order 2^18.I am on a system with 4 GB ( 2**34 Bytes) ram. While allocating memory for my program , i observed something strange. I am using long long qualifier for storing the input in two arrays sum1[1<<17] and sum2[1<<17].So, total memory allocated by the two arrays is 2^17*8 + 2^17*8 = 2^21 Bytes.The part of code i want to refer is :

#include <stdio.h>

int main()
{
    // some code 
    int a=17,b=17;
    long long sum1[1<<a], sum2[1<<b]; 

    // some more code 
}

The problem is that whenever a+b >= 34 , the program stops working, else it works fine.I guess it is due to unavailability of large space. But if i make the two arrays global like that :

#include <stdio.h>

long long sum1[1<<18], sum2[1<<18]; 

int main()
{
    // some code 

}

It works great and doesn't bother about a+b <= 34 , as you can see it works fine for 1<<18.So what's happening under the hood. Regards.

darxtrix
  • 2,032
  • 2
  • 23
  • 30
  • 5
    Because of [Stack Overflow](http://en.wikipedia.org/wiki/Stack_overflow#Very_large_stack_variables) – Yu Hao Jun 16 '14 at 08:13
  • http://stackoverflow.com/questions/11977316/memory-allocation-for-global-and-local-variables has some useful comments on allocation issues – mc110 Jun 16 '14 at 08:15
  • In the second attempt, did anything else change in the application besides moving the `sum1` and `sum2` declaration outside `main()`? – Ja͢ck Jun 16 '14 at 08:35

2 Answers2

2

The local variables for your function go into the stack. Your stack size is not large enough to hold your arrays.

Additional info:

You can see your stack size with the following:

ulimit -s
Arjun Sreedharan
  • 11,003
  • 2
  • 26
  • 34
2

Local variables are usually allocated on the stack, and most systems have a relatively small limit on the size of a stack frame. Large arrays should be either global or allocated dynamically with malloc().

Barmar
  • 741,623
  • 53
  • 500
  • 612