Search code examples
c++objectmemorypointersallocation

C++ memory allocation for objects pointers


#include <iostream>
using namespace std;

class test
{
public:
    int a,b[100];
    test() {
        cout << "Constructor called" << " \n " ;
        a=10;
    }
};

int main()
{
    test a1;    
    test *b2;      
    test *pointer = new test; 

    cout << a1.a << endl;
    cout << pointer->a << " \n ";
    cout << b2->a << " \n ";

    return 0;
}

I would like to know if only two objects are created by the above code, for 'a1' object and 'pointer' object pointer. I assume pointer 'b2' does not get memory allocated for it. In that case, the last " cout << b2->a " should this create a segmentation fault. I am accessing a location whose memory I have not allocated. But I am not getting segmentation fault. Compiler justs prints a random value.

My question are "Are three objects allocated memory here or only two " ? Why there is no segmentation fault ?


Solution

  • a1 is allocated in automatic memory.

    b2 is not an object (well, not an object of the type you defined), but a pointer, and it doesn't point to a valid location. It's a dangling pointer, dereferencing it results in undefined behavior. Anything can happen.

    pointer is a pointer to an object in dynamic memory. It's not an object itself, but it points to the object created by new test.

    Are three objects allocated memory here or only two

    Only two.

    Why there is no segmentation fault ?

    Because undefined behavior means anything can happen. Any behavior is standard-compliant.