Question

Can someone explain me why this C++ code it's behaving this way? And .. how can i avoid this 'vector' problems in the future.

#include <iostream>
#include <vector>
using namespace std;
struct my_str {
    int x;
    my_str() {
        x = 0;
    }
    void insert();
};
vector<my_str> p;

void my_str :: insert() {
    p.push_back(my_str());
    x = 123;
}

int main() {
    p.push_back(my_str());
    p[0].insert();
    cerr << p[0].x;
    return 0;
}
Était-ce utile?

La solution

p.push_back(my_str()); in void my_str :: insert()

causes vector reallocation, this is invalid

x = 123;

BOOM! Heap corruption.

To avoid such problems in future do not edit vectors from objects they contain. Or, if you have to, make sure you do not use object members after this.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top