DCSIMG
Pure Virtual Function Call: Repro Code - All Your Base Are Belong To Us

All Your Base Are Belong To Us

Mostly .NET internals and other kinds of gory details

Pure Virtual Function Call: Repro Code

A few days ago I demonstrated a debugging scenario where one thread attempts to call a virtual function on an object whose destructor is running on another thread. The base destructor restores the virtual function table to that of the base class, which causes the other thread to call a pure virtual function.

The code that I used to reproduce this scenario is really simple, but it’s not (at least for me :-)) immediately evident from reading it that this bug is lurking in the shadows. Here’s the code, anyway:

 #include  <Windows.h> 
 #include  <iostream> 
 
 class  thread {
 private :
 	HANDLE h_;
 	void * context_;
 	static  DWORD WINAPI thread_start(LPVOID p) {
 		thread* pThis = reinterpret_cast <thread*>(p);
 		pThis->work();
 		return  0;
 	}
 public :
	void  start(void * context = nullptr ) {
 		context_ = context;
 		h_ = CreateThread(NULL, 0, thread_start, this , 0, NULL);
 	}
 	virtual  ~thread() {
 		WaitForSingleObject(h_, INFINITE);
 		CloseHandle(h_);
 	}
 protected :
 	virtual  void  work() = 0;
 	void * context() { return  context_; }
 };
 
 class  my_thread : public  thread {
 protected :
 	virtual  void  work() {
 		std::cout << "Inside the thread"  << std::endl;
 	}
 };
 
 int  main(int  argc, char * argv[]) {
 
 	{
 		my_thread t;
 		t.start();
 	}
 
 	return  0;
 }
 

As you can see, the destructor of the my_thread object declared in the main thread might run (and restore the virtual function table to that of the base class, thread) before the static thread_start method has a chance to call the work virtual method. This causes the pure virtual function call.

Comments

Dew Drop – April 30, 2010 | Alvin Ashcraft's Morning Dew said:

Pingback from  Dew Drop &#8211; April 30, 2010 | Alvin Ashcraft&#039;s Morning Dew

# April 30, 2010 3:26 PM

OmariO said:

I know a programm that suffers from this problem.

Now I know the reason.

# May 1, 2010 3:36 AM
Leave a Comment

(required) 

(required) 

(optional)

(required) 


Enter the numbers above: