[GiNaC-list] GiNaC and malloc()

Igor Khavkine igor.kh at gmail.com
Tue Jun 27 19:45:48 CEST 2006


I'm trying to use the GiNaC library as a drop-in replacement for the
native floating point arithmetic between C types. Namely, I have code
which #ifdef's between `typedef double dbl' and `typedef GiNaC::ex dbl',
but keeps actual arithmetic expressions involving dbl's the same between
the different preprocessor paths.

The biggest problem I've run into is memory management. I need to
allocate arrays of type dbl for caching purposes. Since, when not using
GiNaC, the code has to work with a C compiler, I'm constrained to use
malloc() for the allocation. If the GiNaC::ex class had an
initialization routine that could be called on a block of memory, I
would be extremely happy. Because then, I would be able to do something
like:

  GiNaC::ex *expr;
  expr = malloc(sizeof(GiNaC::ex));
  init_ex(expr); /* Or something similar. */
  /* ... Use *expr as a properly constructed instance of GiNaC::ex... */

Since nothing that I could find in the library does what I'd like
init_ex() to do, I tried different ways of implementing it myself.
However, each of the following has prevented me from getting it to work:
- GiNaC::ex overloads the = operator, which expectes the lhs to be
  properly constructed.
- the GiNaC::ex constructor stores references to dynamically allocated
  memory which are freed by the destructor, therefore simply copying the
  class contents to another memory location is not safe.
- GiNaC::ex, as far as I can tell, lacks a "duplicate" or "deep copy"
  routine.

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.

If there is a Right Way (tm) or even just a better way to implement
something like init_ex(), your advice would be much appreciated.

Thanks in advance.

Igor


More information about the GiNaC-list mailing list