Demiu
Demiu

Reputation: 309

Stack overflow while using vector

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.

Upvotes: 0

Views: 172

Answers (3)

Deduplicator
Deduplicator

Reputation: 45704

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]);

Upvotes: 3

Ryan
Ryan

Reputation: 14659

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

Upvotes: 0

Dai
Dai

Reputation: 155708

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.

Upvotes: 1

Related Questions