Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
615 views
in Technique[技术] by (71.8m points)

c++ - Range-based for loop and std::vector.push_back() crashing the program

#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 << "
";
    }
}

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...