I was trying to do something like this:
#include <vector>
#include <algorithm>
int main()
{
int l[] = {1,2,3,4};
vector<int> vi(4);
copy(l, l+4, vi.begin());
do_stuff();
}
The above code can compile and run without no errors. Then I changed it into this:
int main()
{
int l[] = {1,2,3,4};
vector<int> vi;
vi.reserve(4); //different from the above code
copy(l, l+4, vi.begin());
do_stuff();
}
According to the code, I changed vector<int> vi(4); into vector<int> vi; vi.reserve(4);, but the problem comes, that is, the changed code can compile, but a seg-fault occurs when it runs.
According to gdb, the seg-fault occurs in function do_stuff();.
Why is that? Does the change I made matter? Can’t I use reserve here?
The
reserve()method only allocates memory, but leaves it uninitialized. It only affectscapacity(), butsize()will be unchanged.If you want to create as many instances you should use
resize()which allocates memory, and also creates as many instances as the argument passed toresize().