Archived

This topic is now archived and is closed to further replies.

vaceX

New instead of malloc(), -?- instead of _expand() & realloc() ?

Recommended Posts

vaceX    122
What function am I suppoused to use instead of _expand() and realloc() when trying to allocate more memory for the same variable?

Share this post


Link to post
Share on other sites
BriTeg    168
If you''re using new/delete, there isn''t a direct method. What you have to do is create a new allocation, copy the data appropriately, and delete the old one. For example:


  
char *p = new char [10]; // p points to an array of 10 chars

...
// oh no, now we need 20 chars! OK....

char *ptemp = new char [20]; // create a 20-char array

strcpy(ptemp, p); // copy in p

delete [] p; // free the old, unneeded memory

p = ptemp; // and reset p to point to the 20-char array

Share this post


Link to post
Share on other sites
Arild Fines    968
quote:
Original post by BriTeg
strcpy(ptemp, p); // copy in p
[/source]

And what if the array contains something else than a string?



AnkhSVN - A Visual Studio .NET Addin for the Subversion version control system.

Share this post


Link to post
Share on other sites
antareus    576
quote:
Original post by Arild Fines
And what if the array contains something else than a string?

He probably meant memcpy(). I don't use either of those functions myself, since there is std::copy().


[edited by - antareus on May 29, 2003 8:40:02 AM]

Share this post


Link to post
Share on other sites
BriTeg    168
I meant memcpy, because I was thinking a nul-terminated string in my example (hence the char *). But yes, memcpy for non-string, but then you have to also supply the number of bytes you want copied. std::copy is also good, if you''re a namescope type of person. I work with a lot of legacy code where stuff like this isn''t used, so I often forget about it.

Share this post


Link to post
Share on other sites