Archived

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

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

This topic is 5310 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
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
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