0

image

#include <stdio.h>
#include <vector>

using namespace std;

int main()
{
    vector<int> numbers;

    numbers.resize(10001);
    for (int i = 0; i < 10000; i++)
    {
        numbers.push_back(1);
    }

    return 0;
}

If I put more than 5000 1s in the vector, I get the following error, I don't understand.

There is no doubt about it other than the memory overflow. But int type = 4 bytes, so 4byte * 10000 = 40000byte 0.04mb

Why am I getting an error?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
THK
  • 3
  • 2
  • 3
    Use `reserve` instead of `resize` if you're using `push_back`. You can also just use `std::vector numbers(10001,1);` Then there will be no need to use `push_back`. – Jason May 14 '22 at 15:14
  • 2
    Resize sets the size, it will make the vector have `10001` default initialized elements. Then you use `push_back`to add *more* elements. – Some programmer dude May 14 '22 at 15:20
  • 1
    Also, why do you set the size to `10001` and then only (attempt to) use `10000` elements? – Some programmer dude May 14 '22 at 15:21
  • Side note: better to avoid `using namespace std` - see here https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice. – wohlstad May 14 '22 at 15:22
  • 2
    Nothing in the posted code that should cause a memory problem. – doug May 14 '22 at 15:35
  • Is this a [mre]? – Alan Birtles May 14 '22 at 15:50
  • Thanks for your reply. understand. In fact, what I did not understand was that a memory error occurred when data was input to only 10000. before running I was able to solve it as Kim by shutting down the computer. – THK May 15 '22 at 05:01

1 Answers1

0

The error seems unrelated to the code that you've shown.

Now, looking at your code there is no need to use resize and then using push_back as you can directly create a vector of size 10001 with elements initialized to 1 as shown below:

std::vector<int> numbers(10001,1);// create vector of size 10001 with elements initialized to 1

Or you can used std::vector::reserve instead of std::vector::resize, though this is totally unnecessary as you can use the first method shown above.

vector<int> numbers;

numbers.reserve(10001); //use reserve instead of resize
for (int i = 0; i < 10000; i++)
{
    numbers.push_back(1);
}
Jason
  • 36,170
  • 5
  • 26
  • 60
  • The first method works fine. However, the second method produces the same error. – THK May 14 '22 at 15:31
  • @김태후 Can you try reserving some small number like 20 or 30 say by writing `numbers.reserve(20); for (int i = 0; i < 20; i++){numbers.push_back(1);}` and see if it produces the same error. Also, you can/should just use the first method. – Jason May 14 '22 at 15:33