0

I made a program for school's little contest, I have:

#include <iostream> #include <vector> int main(){ int n; std::cin >> n; int c[n]; std::vector<int> r(n); std::cout << "I made it through"; //rest of program } 

When i type in 1000000 and press enter program crashes without a word, exit code (0xC00000FD). I presumed it happens when i initialize vector, but i though it can handle a lot more. Am i doing something wrong? I know i can use pointer but i'd prefer not to touch things that are already working.

1
  • 4
    int c[n]; is the problem. Commented Oct 23, 2014 at 22:34

3 Answers 3

3

The stack is a very restricted resource.

Even though your compiler seems to implement C-style VLA's in C++ (int c[n];), it does not magically gain more memory.

Test 1) Success of reading n, and 2) n not being out-of-bounds for your use before executing the statement allocating that stack-array.

Default stack-size for Windows: 1MB sizeof(int): 4 Thus, about 250000 fit.
Default stack size for Linux: 8MB sizeof(int): 4 Thus, about 2000000 fit.

Workaround: Use dynamic allocation for the ints, like with a std::vector:

std::vector<int> c(n); 

Alternatively, at least use a smart-pointer:

std::unique_ptr<int[]> c(new int[n]); 
Sign up to request clarification or add additional context in comments.

1 Comment

Right, i forgot about c[n]... Now i feel really dumb
1

The problem isn't vector (which uses the heap for its underlying expanding storage in most STL implementations), but int c[n], which will allocate 1,000,000 4-byte integers in the stack, which is almost 4MB. On Win32 the stack is by default around 1MB, hence the overflow.

If you really need to use an array then change your c array to be allocated on the heap by using new, but don't forget to delete[], otherwise use of vector is preferred for most expanding storage scenarios. If you need a fixed-length array then consider array<class T, size_t N> (new in C++11) which adds bounds-checking.

2 Comments

Use vector, not new
std::array is useful but it would blow up the stack the same way the posted code does, the size must be know at compile time, and it only does bounds-checking if you go out of your way to use the at() member function.
0

You probably just need to allocate the array dynamically. In C++

#include <iostream> #include <vector> int main() { int n; std::cin >> n; int *c = new int[n]; if(nullptr == c) { std::cerr << "Runtime error" << std::endl; return 1; } std::vector<int> r(begin(n), end(n)); std::cout << "I made it through"; delete[] c; return 0; } 

Also to make the vector after you have allocated c dynamically you can use begin, end

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.