Orunner
Orunner

Reputation: 424

why is a pointer member initialized to a non-zero?

I came across a strange thing which I cannot explain. A pointer member is not initialized to zero by default (only happens at second time). I know I forgot to initialize it in constructor and to release memory in d-tor. But I cannot explain why the pointer is not initialized to a zero by default. Below is the pseudo code which WORKS. I posted it in order to show you guys what I mean. In my real code, it is far more complex.

My guess so far is there is memory leak somewhere. I would like to hear from you if there are more possibilities. Thanks.

#include <iostream>

class A {
public:
    int *p;
    A () {std::cout << "p in ctor: " << p << std::endl;}
    ~A() {}
    void f(int *i) { p = i;}
};

int main() {
    A *a = new A();
    int c = 0;
    a->f(&c);
    std::cout << "p in step 1:" << a->p << std::endl;
    delete a;
    A *b = new A();
    std::cout << "p in step 2:" << a->p << std::endl;//here works but not in real code
}

Upvotes: 0

Views: 337

Answers (2)

lolando
lolando

Reputation: 1751

If not done explicitely, your members of built-in types are not zero-initialized

Upvotes: 2

Luchian Grigore
Luchian Grigore

Reputation: 258618

But I cannot explain why the pointer is not initialized to a zero by default. - that's how C++ works. It's not initialized to anything. By leaving out the initialization part, you explicitly stated that you don't want it to be initialized.

Upvotes: 8

Related Questions