Home > OS >  Using GMP, omit mpz_clear() after mpz_roinit_n()?
Using GMP, omit mpz_clear() after mpz_roinit_n()?

Time:04-13

The GMP library provides a big int C API and a C API which wraps the C API. Usually you initialize an mpz_t struct (C API) by doing

mpz_t integ;
mpz_init(integ);

(see 5.1 Initialization Functions). When doing so, you later have to free the memory with mpz_clear(integ);. The C API's mpz_class handles this deallocation automatically for you.

Now, if you want to initialize an mpz_t based on existing memory, and you don't want to copy the memory contents, you can use the function mpz_roinit_n() (5.16 Integer Special Functions) for a memory area pointed to by xp:

mpz_srcptr mpz_roinit_n(mpz_t x, const mp_limb_t *xp, mp_size_t xs)

This initializes x in a special way so it can be used as a read-only input operand (hence the ro in the function name) to other mpz function. Now, the documentation of mpz_clear(integ) says this:

Free the space occupied by x. Call this function for all mpz_t variables when you are done with them.

I wonder if mpz_t's which have been initialized with a call to mpz_roinit_n() are an exemption to this rule, because they don't need to be deallocated.

If I'm correct, this would also mean that mpz_roinit_n() can't be used with the C API's mpz_class, not even with mpz_class.get_mpz_t(), because mpz_class's destructor always tries to deallocate the underlying mpz_t, and this would cause memory issues. Am I correct here?

CodePudding user response:

mpz_clear does nothing on a mpz_t set with mpz_roinit_n. So you don't need to call it, but it is still safe if it gets called.

  • Related