user1543957
user1543957

Reputation: 1838

Declaring array causing error

I am unable to execute the below code in codeblock ide but if I declare the array globally then I can execute it.
What are the limits on array size when declared globally and when declared locally ? What is the thumb rule for declaring array size in competitive programming contest like spoj, codechef etc?
Also if the error is due to codeblock ide. Then how can I correct it ?

#include<iostream>

using namespace std;


int main()
{
    int arr[999999];

    return 0;
}

Upvotes: 8

Views: 518

Answers (3)

Agentlien
Agentlien

Reputation: 5136

The reason this is disallowed is because it would add a total of 999999*sizeof(int) bytes (7.6MiB in a typical 64-bit environment) to the stack frame of main(), which is a very large amount of memory for a single stack frame.

The maximum size of a stack frame depends on your implementation and environment settings.

If you do need this memory, you should either locate it statically (using a static variable) or dynamically, depending on whether you need to have multiple calls of main() inside your program. If you settle for dynamic memory, consider using a vector instead and using std::vector<int> arr(999999); in order to declare a vector with the initial size set to 999999.

Upvotes: 7

JohnTortugo
JohnTortugo

Reputation: 6625

Generally speaking, variables declared in global scope are "allocated" in the .data or .bss section of a ELF executable file. Variables, including vectors, declared inside a method/function are allocated dynamically from the stack when the method/function is executing. The size of the stack is dependent of operating system.

So, in summary this error is most likely due to stack overflow =D

In a programming contest (spoj, topcoder, icpc, codejam, etc.) is a good idea to declare you vector dynamically. Be it using vector, malloc or new. This guarantee that you use only the needed amount of memory.

Upvotes: 4

111111
111111

Reputation: 16168

Without the exact error (can you provide this?) it's hard to say exactly what's happen but more likely than not you are getting a stack overflow. The specific size of the stack is iplementation defined, mosst platform provide a mean of enlarging it.

The easiest and most correct solution to this problem is to use a managed standard container to hold the array like a std::vector, this will allocate onto the freestore and manage the memory for you as well as provide a consistant interface.

#include <vector>
int main() {
     std::vector<int> arr (999999);
     return 0;
}

As a general rule, prefer containers to raw arrays there is very little if any overhead.

Reference

http://en.cppreference.com/w/cpp/container/vector

Upvotes: 5

Related Questions