Increasing Size of Vector


HI, I need to increase the size of my vector. However the program crashes.
How do I increase the size and prevent it from crashing. Below is the vector in question.

Thanks.


1
2
3
4
    const size_t width = 256, height = 256;
    size_t no_elems = width * height * 4;
    using Image = std::vector<unsigned char>;
    std::vector<Image> Image_PNG(6000, Image(no_elems));
Last edited on
You can resize a vector using the resize member function.

 
vec.resize(new_size);
or
 
vec.resize(new_size, value_of_new_elements);
Last edited on
When I do that I get an "Unhandled Exception: System.AccessViolationExeption: Attempted to read or write protected memory. This is often an indication that other memory is corrupt"
We don't have enough information to tell what is wrong. It might be that you're accessing an array element out of bounds (e.g. Image_PNG[6005].resize(85000);) but it could also be something completely unrelated. UB/memory corruption does not necessary crash right away but can sometimes cause bugs in other parts of the program. Using a memory debugger such as valgrind (not available on Windows) or an UB/address sanitizer (supported by all major compilers, e.g. with GCC you can enable it using the compiler flag -fsanitize=address,undefined) can often help you find these kind of problems (the cause, which is not necessarily close to where the crash happens). Otherwise if you cannot figure it out yourself I recommend creating a minimal example that demonstrates the problem and post it here so that we can have a look. https://en.wikipedia.org/wiki/Minimal_reproducible_example
Last edited on
Registered users can post here. Sign in or register to post.