I want to resize an array of objects. I found an earlier thread which requested the same, where post 14 suggested what to do. I made my custom operator new[] and delete[] as described in the article Customized Allocators with Operator New and Operator Delete by Andrei Millea on this site. In this way I can use realloc to resize my array, but the implementation of new[] offsets the address of the ptr by 4 bytes (most likely to store the length of the array). But this makes it completely ..........y to resize. Since I don't know the real address of the memory block. It may be that the offset is implementation dependent or is 8 bytes in 64-bit mode.
An example of code to illustrate the problem reads:
Is this the proper approach to resizable arrays?Code:class Myclass { public: void* operator new[](size_t); }; void* Myclass::operator new[](size_t size) { void *storage = malloc(size); if(NULL == storage) { throw "allocation fail : no free memory"; } return storage; } int main(void) { Myclass *MyArrayOfMyClass,*ExpandedArrayMyOfClass; MyArrayOfMyClass = new Myclass[10]; // I need to resize my array of objects ExpandedArrayMyOfClass = (Myclass*)realloc (MyArrayOfMyClass, sizeof(Myclass)*((size_t)(20)) ); // <- So this is unsafe, because I allocate 4 bytes too less. // and the real base of the memoryblock of MyArrayOfMyClass is &(((char*)MyArrayOfMyClass)[-4]) }
How to get the real memory address and required length for MyArrayOfMyClass?
On my system, memory is 16 byte alligned, so any ptr should have an address ending on 0 (example 0x1001c0), but can I rely on this?
And I don't want to use std::vector