Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Range-based for loop and std::vector.push_back() crashing the program [duplicate]

Tags:

c++

c++11

#include <iostream>
#include <vector>

int main() {
    std::vector<int> vec;
    for (int i = 0; i < 42; ++i) {
        vec.push_back(i);
        vec.push_back(-i);
    }
    for (int x: vec) {
        for (int y: vec) {
            vec.push_back(x + y);
        }
    }
    for (int x: vec) {
        std::cout << x << "\n";
    }
}

What's causing this code to crash? I tried compiling it with -fsanitize=address, got ==9347==ERROR: AddressSanitizer: heap-use-after-free on address 0x61500000fdb4 at pc 0x00010a4f1043 bp 0x7fff55710b70 sp 0x7fff55710b68. It fails at vec.push_back(x + y) when x == 0 and y == 22 on my computer.

like image 640
xcusazyt Avatar asked Nov 29 '25 15:11

xcusazyt


1 Answers

From std::vector::push_back :

If the new size() is greater than capacity() then all iterators and references (including the past-the-end iterator) are invalidated. Otherwise only the past-the-end iterator is invalidated.

Range-based for loop uses iterators internally. Using push_back may cause these iterators to be invalidated.

Edit : Notice that when y == 22 you are inserting a 65th element into your vector. It's likely the capacity was 64. Many implementations increase capacity by powers of 2 (doubling it each time).

like image 58
François Andrieux Avatar answered Dec 02 '25 05:12

François Andrieux



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!