SEGFAULT - On C++ pure virtuals. Why?
I am passing a pure-virtual base class pointer arround through C code as a void *
.
When I dereference the base class in C++, the debugger is able to access all of its members. However, when I attempt to access a pure virtual function it SEGFAULTs/Access Violation. "Cannot access memory at 0xc" says the debugger (when I attempt to access a pure virtual fun开发者_C百科ction).
It is possible that the function is being called before the constructor returns, would this matter? What else should I look for? All the other variables seem to be intact.
Code:
the_socket_base* thisptr = reinterpret_cast<the_socket_base*>(watcher->data);
thisptr->CallPureVirtualFunction();
delete thisptr;
thisptr->CallSecondPureVirtualFunction(); //OOPS! It crashed
...
watcher->data = this; // Associate socket with the watcher (Where 'this' is the base class)
// NOTE THAT THE ABOVE ALWAYS HAPPENS IN THE CONSTRUCTOR
UPDATE: The code is partially working and I do suspect that the object gets deleted. Because it runs the read handler (which can delete itself) and then it runs the write handler without checking... So that's probably what it is.
Answer
FINAL UPDATE: I wanted to clarify that Keith's comment was correct. I was deleting an object and trying to access it after it was deleted. Very simple mistake! delete this;
is a tricky pitfall. Thanks for all the comments.
Without code, hard to say. Two possibilities OTOH:
- You're calling virtual functions directly or indirectly from constructor or destructor - you cannot do that.
- You're using multiple inheritance - and your casting via a void * breaks
delete this; // Is dangerous, use with care
What I was doing is delete this; in the pure virtual function, returning immediately, and then calling another pure virtual function on the already deleted object.
- Pure virtual vtable will fail when object has already been deleted
精彩评论