Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static pointer and operator new

Tags:

c++

class X {
public:
    X(int i) : num(i){}
    int num;
};

void f(int i){

    static X* px1 = new X(i);
    X* px2 = new X(i);
    cout<<px1->num;
    cout<<px2->num<<' ';

};

void main(){
    for (int i=0;i<5;i++) 
        f(i);
}

This code will output 00 01 02 03 04, but I don't quite understand why static pointer px1 can't change its value using operator new.

Also, this code has memory leakage problem. Can I use delete with px1? Will using delete on both pointers solve memory leakage problem?

like image 516
scarably Avatar asked May 19 '26 08:05

scarably


1 Answers

That's because static locals are initialized only once when control first passes through the initialization code. So although you call the function multiple times the following line:

static X* px1 = new X(i);

will only be executed in the very first call (with i being zero) and the variable will persist its value between the function calls.

Yes, you can delete px1 but you'd better set it to null afterwards to avoid double-free and undefined behavior. You also have leaks with objects pointed to by px2 - you have to take care of those objects too.

like image 96
sharptooth Avatar answered May 21 '26 22:05

sharptooth