[ODE] Re: ALLOCA
Olivier Michel
Olivier.Michel at cyberbotics.com
Thu Mar 4 11:06:31 MST 2004
Hi,
I finally found a solution:
#ifdef dDYNAMIC_MEMORY_ALLOCATION
class StackMemory {
public:
StackMemory( int size ) {
ptr_ = malloc( size );
}
~StackMemory() {
free( ptr_ );
}
void * ptr_;
};
#define ALLOCA(t,v,s) \
StackMemory alloca_ ## v ( s ); t* v = (t*)alloca_ ## v .ptr_
#else
#define ALLOCA(t,v,s) t* v=(t*)dALLOCA16(s)
#endif
[...]
ALLOCA (dReal,tmprow,n * sizeof(dReal));
[...]
Which works nicely. I will now try to avoid using the vanilla malloc /
free and use the replacement functions you posted:
> char * block;
> size_t top;
>
> void init_alloca()
> {
> block = malloc( MAX_ALLOCA_SIZE );
> // maybe do something that aligns "block" on 16 bytes
> top = 0;
> }
>
> void * alloca( size_t size )
> {
> // round size to good alignment
> size = (size + 15) & -16;
> top += size;
> assert( top <= MAX_ALLOCA_SIZE );
> return block+top-size;
> }
>
> void * freea( void const * ptr )
> {
> top = min( top, (char const *)ptr - block );
> }
Olivier Michel wrote:
> Hi,
>
> I tryed to implement the clever C++ ALLOCA macro to save us from the
> FREEA macro, but I cannot get it work:
>
> #ifdef dDYNAMIC_MEMORY_ALLOCATION
>
> class StackMemory {
> public:
> StackMemory( int size ) {
> ptr_ = malloc( size );
> }
> ~StackMemory() {
> free( ptr_ );
> }
> void * ptr_;
> };
>
> #define ALLOCA(t,v,s) \
> StackMemory alloca_ ## __LINE__( s ); v = (t*)alloca_ ## __LINE__ .ptr_
>
> #else
> #define ALLOCA(t,v,s) v=(t*)dALLOCA16(s)
> #endif
> [...]
> dReal *AA,*dd,*bb;
> ALLOCA (dReal,AA,n*nskip*sizeof(dReal));
> ALLOCA (dReal,dd,n*sizeof(dReal));
> [...]
>
> Here is what I get with gcc 2.96:
>
> gcc -c -Wall -fno-rtti -fno-exceptions -Wall -fomit-frame-pointer
> -ffast-math -Iinclude -DdNODEBUG -DdDYNAMIC_MEMORY_ALLOCATION -O2 -o
> ode/src/lcp.o ode/src/lcp.cpp
> ode/src/lcp.cpp: In function `void dSolveLCPBasic (int, dReal *, dReal
> *, dReal *, dReal *, int, dReal *, dReal *)':
> ode/src/lcp.cpp:1024: redeclaration of `StackMemory alloca___LINE__'
> ode/src/lcp.cpp:1023: `StackMemory alloca___LINE__' previously declared
> here
>
> Apparently it is unable to expand the __LINE__ inside a macro... Any
> hint ?
>
> -Olivier
>
> Jon Watte wrote:
>
>> Regarding ALLOCA, you might not need a FREEA() macro, if you
>> structure the
>> macro something like so:
>>
>> class StackMemory {
>> public:
>> StackMemory( int size ) {
>> ptr_ = malloc( size );
>> }
>> ~StackMemory() {
>> free( ptr_ );
>> }
>> void * ptr_;
>> };
>>
>> #define ALLOCA(v,s) \
>> StackMemory alloca_ ## __LINE__( s ); v = alloca_ ## __LINE__ .ptr_
>>
>>
>> Note that this macro needs to take the assigned-to variable as well
>> as the
>> size, rather than just the size.
>>
>> Cheers,
>>
>> / h+
>
More information about the ODE
mailing list