vendredi 24 février 2017

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 << "\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.

Aucun commentaire:

Enregistrer un commentaire