[quote name='Lauris Kaplinski' timestamp='1309640193' post='4830463']
I have used realloc extensively in both C and C++ programs and have not had any problems. Right tool for the right job
How to do it properly? I will use memory pools anyway, but I need to finish that class I have begun.
And I'm not really a beginner, however I am not educated programmer, but fluid mechanics engineer, so many things for me are unclear.
I'm just an user of programming.
[/quote]
MyType *newptr = (MyType *) realloc (oldptr, newsize * sizeof (MyType));
for (size_t i = oldsize; i < newsize; i++) {
// Initialize your new data here
}
- Do not try it with non-POD types! Although there is placement new, things get ugly fast.
- Do not forget, that the block address may change - thus you should NOT keep extra pointers to it.
- Do not forget, that your old memory block may be freed and completely new one allocated. Thus you cannot keep pointers to individual objects.
- Your old objects (datablocks) will be copied bit-by-bit. If this is not the intended behaviour, do not use it.
- Your new objects (datablocks) will be uninitialized - i.e. filled with arbitrary garbage.
- If new memory block is allocated, neither destructors nor copy contructors are called
- It is better to avoid MyType constructors altogether. Then you cannot expect it to be called (it won't).
In general, there should be very good reasons to use malloc/realloc/free in C++ code. One possible cause is to reduce unnecessary pointer dereferencing - something like:
struct VectorPath {
unsigned int size;
unsigned int nelements;
Rect bbox;
float coordinates[2];
};
In this example you can construct paths of arbitrary length by allocating more memory than the size of given struct and then access coordinates >= 2. I think this may be violating C/C++ standard, but I do not think there is or will be any compiler that does not support it. But in any case such constructs require good and clean encapsulation - or they'll bite you.
My suggestion is - use new/delete and copy manually, or use vectors. Encapsulate the required behaviour into clean API and get your program working. Then you can experiment with more esoteric things ;-)