Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: C++
Expertise: Intermediate
Jan 9, 2001



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Using Memset On Class Objects

It's common practice in C, to do a memset on structures, in order to initialize all member variables to some default value, usually NULL. Similarly, you can use memset to initialize class objects. But what happens if the class contains some virtual functions?

Let's take an example:
class GraphicsObject{
	char *m_pcName;
	int    m_iId;
	virtual void Draw() {}
	virtual int Area() {}
	char* Name() { return m_pcName;}

class Circle: public GraphicsObject{
	void Draw() { /*draw something*/ }
	int Area() { /*calculate Area*/ }

void main()
	GraphicsObject *obj = new Circle; //Create an object
	memset((void *)obj,NULL,sizeof(Circle)); //memset to 0
	obj->Name(); //Non virtual function call works fine
	obj->Draw(); //Crashes here

This results in a crash, because every object of a class containing virtual functions contains a pointer to the virtual function table(vtbl). This pointer is used to resolve virtual function calls, at run time and for dynamic type casting. The pointer is hidden, and is not accessible to programmers by normal means. When we do a memset, the value of this pointer also gets overwritten, which, in turn, results in a crash, if a virtual function is called.

To avoid such mysterious crashes, memset should not be used on the objects of a class with virtual functions. Instead use the default constructor or an init routine to initialize member variables.
Nitin Kumar
Thanks for your registration, follow us on our social networks to keep up-to-date