Memory re-allocation

Memory re-allocation

Is there a standard method/operator in C++ analogous to standard C’s realloc() function that enables resizing of dynamic memory allocated by new operator?

There is no standard call defined in C++ to reallocate memory once it has beencreated using new. The easiest way of doing it is to new a block of therequired size, copy the memory over to the newly allocated block and deletethe old block.

For example:

void MyClass::reallocate (){	char * tmpBlk = new char[5000]; // new size	memcpy(tmpBlk,data_,data_size); // assume old block is data and data_size									// is size of data_	delete [] data_ ; // de-allocate old data	data_ = tmpBlk;}
Note that if there were any references to data before, they will become invalid at this point. So great care must be taken when using thistechnique.

See also  The Art of AI-Generated Meeting Minutes

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