'vector push_back memory access denied in Visual Studio
#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?
Solution 1:[1]
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);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Anoop Rana |

