[GiNaC-list] GiNaC and malloc()

Richard B. Kreckel kreckel at ginac.de
Tue Jun 27 21:50:28 CEST 2006


Igor,

Igor Khavkine wrote:

> My current best solution, is something like:
>
>  GiNaC::ex *expr, *expr_lost = new GiNaC::ex();
>  expr = malloc(sizeof(GiNaC::ex));
>  memcpy (expr, expr_lost, sizeof(GiNaC::ex));
>
> Unfortunately, unless I take extra steps to keep track of memory pointed
> to by expr_lost, it gets leaked.


I don't think you can get around those "extra steps" you mention.  In 
C++, one has placement new for directed allocating.  But you would have 
to write some additional code between #ifdefs to use it instead of 
malloc(3).  And even doing so would not spare you extra destructor calls 
to avoid leaks.  This function does not leak:

void f(size_t n)
{
    char buf[n*sizeof(GiNaC::ex)];  // you manage that memory!
    for (size_t i=0; i<n; ++i) {
        new(&buf[i*sizeof(GiNaC::ex)]) GiNaC::ex(2);
    }

    //...
    cout << *reinterpret_cast<GiNaC::ex*>(&buf[0 * sizeof(GiNaC::ex)]) 
<< endl;
    //...

    // It is your responsibility to keep track of the reference counts:
    for (size_t i=0; i<n; ++i) {
        reinterpret_cast<GiNaC::ex*>(&buf[i*sizeof(GiNaC::ex)])->~ex();
    }
}

Not sure if this helps.

Regards
  -richy.

-- 
Richard B. Kreckel
<http://www.ginac.de/~kreckel/>



More information about the GiNaC-list mailing list