Re: Is it ever unsafe to realloc?
On Thursday, July 12, 2012 3:19:36 PM UTC-4, Seungbeom Kim wrote:
On 2012-07-11 18:40, fmatthew5876 wrote:
Suppose I have a pool of memory (say a dynamic array) that I
allocate using malloc(), cleanup using free(), and use placement new
and explicit destructor calls to handle constructors/destructors.
If I want to resize this memory pool (invalidating any iterators/
pointers to objects in the pool) can I safely call realloc() to do it
no matter what kind of C++ objects are being stored? Are there some
classes of C++ types where I have to allocate a new pool using malloc()
and use move/copy constructors? If so what are the cases where realloc
is not safe?
realloc() potentially allocates a new block and bit-copies (as with
memcpy()) the old contents into the new block. This is safe for POD
objects, but not in general: the copy (or move) constructor should
handle the relocation.
{ quoted signature and banner removed -mod }
{ Please limit your text to fit within 80 columns, preferably around 70,
so that readers don't have to scroll horizontally to read each line.
This article has been reformatted manually by the moderator. -mod }
By why do copy/move constructors have to always be called? Can some
objects maintain internal pointers to parts of themselves in vtables?
For instance with virtual functions and/or virtual inheritance?
For instance when would this be unsafe?
class A {
//stuff
};
A* ptr = (A*)malloc(sizeof(A)*2);
new (ptr) A();
new (ptr+1) A();
ptr = (A*) realloc(ptr, sizeof(A) * 3);
new (ptr+2) A();
ptr[0].~A();
ptr[1].~A();
ptr[2].~A();
free(ptr);
or this?
A* ptr1 = (A*)malloc(sizeof(A));
A* ptr2 = (A*)malloc(sizeof(A));
new (ptr1) A();
memcpy(ptr2, ptr1, sizeof(A));
ptr2.~A():
free(ptr1);
free(ptr2);
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]