[ODE] Memory allocation

Andrzej Szombierski qq at kuku.eu.org
Mon Oct 4 18:54:26 MST 2004


On Mon, 4 Oct 2004, Jon Watte wrote:

> 
> > int * a = new int[variable];
> > [...]
> > delete [] a;
> 
> That's true for arrays, but not true for single instances.
> And, in fact, the delete has to be done through the type that 
> was allocated. The only thing stored in the array is the number
> of elements in the array, and the compiler will multiply by the 
> type that's deleted. Witness the output:
> 
[...]

You're right, thanks for pointing this out :)

> 
> If you need the correct size of the object, you have to put it 
> in your allocation. You could change dBase to do something like:
> 
>   void * operator new( size_t s ) {
>     size_t * sp = (size_t *)my_malloc( s + sizeof(size_t) );
>     *sp = s;
>     return sp+1;
>   }
>   void operator delete( void * ptr, size_t s ) {
>     size_t * sp = ((size_t *)ptr)-1;
>     my_free( sp, *sp + sizeof(size_t) );
>   }
> 

Actually malloc() itself does something similiar to this to store 
the size of the block (at least the glibc version). My point is that as 
long as you don't change the memory allocation functions everything will 
work fine, since the default ones know the block size themselves (free() 
has no size argument).

-- 
:: Andrzej Szombierski :: qq at kuku.eu.org :: http://kuku.eu.org ::
:: anszom at bezkitu.com  :: radio bez kitu :: http://bezkitu.com ::



More information about the ODE mailing list