Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Beginner
May 2, 1997

Memory re-allocation

Question:
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?

Answer:
There is no standard call defined in C++ to reallocate memory once it has been created using new. The easiest way of doing it is to new a block of the required size, copy the memory over to the newly allocated block and delete the 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 this technique.
DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date