Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What could this curious combination of "while" and "delete" mean?

Reviewing a quite old project I found the following curious code snippet (only relevant code extracted):

class CCuriousClass {
    ~CCuriousClass();
    CSomeType* object;
};

CCuriousClass::~CCuriousClass()
{
    while( object != NULL ) {
        delete object;
    }
}

Have I overseen anything or is it a plain road to undefined behaviour?

What I see here is that if object is a null pointer at the point of CCuriousClass::~CCuriousClass() being called everything will be fine - no action taken - but if object is not null this will be an infinite loop with undefined behaviour inside.

Is this most likely a bug or some smart construct I don't understand?

like image 666
sharptooth Avatar asked Nov 28 '22 00:11

sharptooth


2 Answers

This looks like a bug.

like image 147
Andreas Brinck Avatar answered Dec 19 '22 06:12

Andreas Brinck


It could be that some lunatic has implemented CSomeType with a back-reference to its owning CCuriousClass, and its destructor sometimes creates a replacement. Something like this:

class CSomeType
{
public:
    explicit CSomeType(CCuriousClass &parent) : parent(parent) {}
    ~CSomeType()
    {
        parent.object = respawn() ? new CSomeType(parent) : 0;
    }
private:
    CCuriousClass &parent;
};

I'm not suggesting that anyone should ever write such twisted logic. It probably still gives undefined behaviour, since I believe delete is allowed to modify the pointer. But it might explain why someone might think the given code might be valid.

On the other hand, it's probably just a bug caused by a misunderstanding of how delete works.

like image 44
Mike Seymour Avatar answered Dec 19 '22 06:12

Mike Seymour