0

So...

I've set up Boehm's GC and want to make the GMP library use it.

This is what I'm doing right now:

    //===================
    // Definitions
    //===================

    #include <gc.h>

    #define MALLOC(x)       GC_malloc(x)
    #define XALLOC(x)       GC_malloc_atomic(x)
    #define CALLOC(n,x)     GC_malloc((n)*(x))
    #define REALLOC(p,x)    GC_realloc((p),(x))
    #define FREE(x)         (x) = NULL
    #define FREENOW(x)      GC_free(x)

    //===================
    // Helpers
    //===================

    void* allocate_function (size_t alloc_size) {
        return MALLOC(alloc_size);
    }

    void* reallocate_function (void *ptr, size_t old_size, size_t new_size) {
        return REALLOC(ptr, new_size);
    }

    void deallocate_function (void *ptr, size_t size) {
        FREE(ptr);
    }

    //===================
    // Main code
    //===================

    int main(int argc, char** argv) {

        mp_set_memory_functions(&allocate_function, 
                                &reallocate_function, 
                                &deallocate_function);

        // ...
        // rest of the code
        // ...
    }

Am I doing it right?

Is there anything to take into account?

Dr.Kameleon
  • 22,532
  • 20
  • 115
  • 223
  • The `#define`s have no purpose in your source module. The may be moved to the header for use by the using modules. – Paul Ogilvie Dec 26 '19 at 13:33
  • Your `allocate_function` and other functions should be in a separate source file. – Paul Ogilvie Dec 26 '19 at 13:34
  • Where/how is `GC_free` used? – Paul Ogilvie Dec 26 '19 at 13:36
  • @PaulOgilvie That's exacly how it is, I put it all in here just to showcase my code. – Dr.Kameleon Dec 26 '19 at 13:45
  • What happens mostly is pointers being set to `NULL` instead of directly using `GC_free` – Dr.Kameleon Dec 26 '19 at 13:46
  • Doesn't the library redefine malloc/realloc/free? Linking with it before libc should be sufficient. Or do you want some strange mix where only GMP uses the GC? – Marc Glisse Dec 26 '19 at 17:08
  • I tried to do the same and came to the conclusion that GMP works with the Boehm GC only due to accidental compatibility. If you need a GC, you probably cannot call all mp*_clear functions, so you must rely on them doing nothing else but freeing space (instead of, say, unlinking from an internal list, which would keep the allocated space indefinitely if *_clear was omitted), and - this is just a performance issue - you cannot safely use malloc_atomic as there's no guarantee the GMP allocation routines aren't used to create internal pointer-linked structures. – Kryptozoon Sep 29 '20 at 08:25

0 Answers0