[ODE] Memory allocation

Jon Watte hplus-ode at mindcontrol.org
Mon Oct 4 09:14:35 MST 2004


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

new(16)                 (one baz16)
delete(1)               (sizeof(foo) == 1)
new(16)                 (one baz16)
delete(16)              (sizeof(baz16) == 1)
new[](84)               (sizeof(bar8) == 8, times 10, plus 4 for element count)
delete[](14)            (sizeof(foo) == 1, times 10, plus 4 for element count)
new[](84)               (sizeof(bar8) == 8, times 10, plus 4 for element count)
delete[](84)            (sizeof(bar8) == 8, times 10, plus 4 for element count)

(test program attached below)


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) );
  }


Cheers,

				/ h+




#include <stdlib.h>
#include <stdio.h>
#include <new>


char temp[100];

class foo {
  public:
    void * operator new( size_t s ) { printf( "new(%d)\n", s ); return temp; }
    void operator delete( void * ptr, size_t size ) { printf( "delete(%d)\n", size ); }
    void * operator new[]( size_t s ) { printf( "new[](%d)\n", s ); return temp; }
    void operator delete[]( void * ptr, size_t size ) {printf( "delete[](%d)\n", size ); }
};

class bar8 : public foo {
  public:
    int a;
    int b;
};

class baz16 : public bar8 {
  public:
    int c;
    int d;
};

int
main()
{
  foo * f = new baz16;
  delete f;

  f = new baz16;
  delete (baz16 *)f;

  f = new bar8[10];
  delete[] f;

  f = new bar8[10];
  delete[] (bar8 *)f;

  return 0;
}





More information about the ODE mailing list