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 ? */
No, it is not true.
deletedoes not set pointer toNULL. It merely deallocates the memory allocated to the pointer and calls appropriate destructors.On other hand calling
deleteon aNULLpointer is a No-Op. So it is not required to check forNULLbefore callingdelete.Note that explicitly
NULLing the pointer afterdeleteshall 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.