1

When I run the following code in C language, my compiler shows the error "xxx has stopped working ".

However, when I take array sizes as 1000 instead of 100000 it runs fine. What is the problem and how can I fix it? If there is some memory problem then how can I take input of 100000 numbers in these arrays without exceeding it?

Code I tried :

int main()
{
    int a[100000],l[100000],r[100000],ans[100000],x[100000],y[100000];
    /*
    some code
    */
    return 0;
}
2
  • 2
    Was the error Stack Overflow? Stack is nearly 1MB order but heap is limited to memory. You should use malloc() and free() Commented Aug 9, 2013 at 12:24
  • You're probably overrunning the stack Commented Aug 9, 2013 at 12:24

5 Answers 5

3

Declare a, l, r, ans, x and y as global variables so that they will be allocated in the heap instead of the stack.

int a[100000], l[100000], r[100000], ans[100000], x[100000], y[100000];
int main()
{
Sign up to request clarification or add additional context in comments.

Comments

3

The stack is typically a limited resource. Use dynamic allocation (such as malloc) instead.

Comments

2

Most systems limits the stack to something between one and four megabytes. Since your arrays are well over 2MB you are most likely going over the stack limit of your system.

In C there are a couple of ways to solve that problem:

  • Make the arrays global
  • Make the arrays static
  • Dynamically allocate the memory for them of the heap (e.g. malloc and friends)
  • Simply make the arrays smaller

1 Comment

The default is 8 MiB on OS X.
2

Welcome in stackoverflow ;)
use dynamic allocation (malloc/free) in order to use all your ram capacities.

1 Comment

i see what you did there ;)
0

Most systems have a limited stack size and since your arrays are local(automatic) variables they will be allocated on the stack, so you are very likely overflowing the stack. If you need to allocated large arrays malloc is going to be the better choice.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.