1
void EventCloseServer::act(){
    Server* serv = Program()::getServer();
    if (serv != NULL) {
        if (serv->running()) {
            serv->stop();
            serv->sync();
        }
        delete (serv);
    }
}

The problem arises when I execute this code twice. The first time, the function gets to delete(serv) alright. The second time, it causes segmentation fault before the call to serv->running() and after serv != NULL. I don't understand why the second execution gets inside the first if statement. Isn't it true that the following will result in myObject = NULL?

Class* myObject = new Class();
/***/
delete(myObject); /* myObject = NULL ? */

2 Answers 2

4

No, it is not true.
delete does not set pointer to NULL. It merely deallocates the memory allocated to the pointer and calls appropriate destructors.

On other hand calling delete on a NULL pointer is a No-Op. So it is not required to check for NULL before calling delete.

Note that explicitly NULLing the pointer after delete shall seem to solve your problem but it might hide problems in your code.The best way to solve this is to use Smart pointers and not raw pointers which need explicit memory management.

1

After deleting serv needs to be set to NULL. Not the local variable, but the one which is returned by Program()::getServer().

Assuming there is a Program()::setServer

delete(serv);
Program()::setServer(NULL);

Reusing a deleted pointer is recipe for a crash. And deleting a pointer doesn't set it to NULL.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.