Using Memset On Class Objects

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{protected:	char *m_pcName;	int    m_iId;	//etcpublic:	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.

See also  Monetize TikTok For Your Business

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist