Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Strange std::vector behaviour with structures while trying to assign a pointer to structure member

I just don’t know how to describe this problem better. I have the following code (i wrote using namespace std to simplify it):

#include <iostream>
#include <vector>

using namespace std;

struct Vertex
{
    int num;
    Vertex* path;
};

int main()
{
    vector<Vertex> vertexes{};
    for (int i = 0; i < 2; i++)
    {
        vertexes.push_back({ i + 1, nullptr });
        vertexes[i].path = &vertexes[i];
        
        cout << vertexes[i].num << ": " << vertexes[i].path->num << endl;
    }
    
    cout << endl;
    
    for (Vertex& vertex : vertexes)
    {
        cout << vertex.num << ": " << vertex.path->num << endl;
    }

    return 0;
}

The online compiler output:

1: 1
2: 2

1: 1579877676
2: 2

What am i doing wrong and where the first pointer is getting invalidated?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

https://en.cppreference.com/w/cpp/container/vector/push_back

If after the operation the new size() is greater than old capacity() a reallocation takes place, in which case all iterators (including the end() iterator) and all references to the elements are invalidated.

Your code doesn’t check whether this is happening, but it’s likely that it happens on the second push_back, in which case the pointer (iterator) to vertexes[0] may be invalidated.

If you want this to work then you can use reserve to increase the capacity to a sufficiently large value before you start. Or use a different container such as list.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading