Why static vector of pointer to objects of a class is having garbage values?

I am doing a project on OOPs in C++ and getting some errors (Segmentation Fault).

sObjects is a static vector containing pointers to every object created in the Base class.

I have also checked the addresses by uncommenting the lines : // cout<<(*it)<<endl; // cout<<this<<endl; .They are same.

So why I am getting garbage values/segmentation fault ? Do I have to do some sort of casting?

Here is my code:

#include <iostream>
#include "Base.h"
using namespace std;

int main()


    vector<Base *>::iterator it;
    for (it = Base::sObjects.begin(); it < Base::sObjects.end(); ++it)
        // cout<<(*it)<<endl;

    return 0;
#ifndef BASE_H
#define BASE_H

#include <iostream>
#include <vector>
using namespace std;

struct Node{
    int val;

class Base
    Node node_;
    Base(int a=0);

    static vector<Base*> sObjects;
    friend ostream &operator<<(ostream &os, const Base &myObj);

    static void UnitTest();

#include "Base.h"
vector<Base*> Base::sObjects;

Base::Base(int a)
    // cout<<this<<endl;


ostream &operator<<(ostream &os, const Base &myObj)
    return os;

void Base::UnitTest()
    Base obj(23);


The object created in Base::UnitTest() goes out of scope however you keep its pointer to it using sObjects.push_back(this); in your vector after it no longer exists. This is an instance of a dangling pointer. This is undefined behavior. Anything can happen including it appearing to work some of the time. Thankfully you found that it does not work in your case. It would have been much worse if it appeared to work even though it was broken.

Related: What is a dangling pointer?

Also: What are all the common undefined behaviours that a C++ programmer should know about?

In the also link this is a case of using a pointer who’s lifetime has ended. Using pointers to objects whose lifetime has ended (for instance, stack allocated objects or deleted objects)

Leave a Reply

Your email address will not be published. Required fields are marked *