I need to generate a temporary big integer, then later, if certain conditions are satisfied, move it to permanent storage. This can be done with the usual functions:
mpz_t temp;
mpz_init_set_str(temp, "99999999999999999999999999999999999999999");
// other things happen, including the allocation of perm
// as suitable permanent uninitialized storage
mpz_init_set(perm, temp);
mpz_clear(temp);
But this is inefficient. temp
points to a chunk of heap memory to store the actual digits. Then perm
allocates its own chunk of heap memory to copy the digits into. Then temp
's heap memory is freed. It would be much more efficient to transfer ownership of the heap memory from temp
to perm
, and then just refrain from clearing temp
, but I don't see any mention in the documentation about a function to do that.
This might be done with memcpy(perm, temp, sizeof temp)
. Logically this should work, but I don't think it's guaranteed by the API, and I would ideally prefer a solution that is.
What about mpz_swap
? The documentation says it swaps two values efficiently, which means it should suffice for this case, but doesn't say anything about whether it's guaranteed to work if one of the variables is uninitialized.
Is there something else I am missing?
question from:
https://stackoverflow.com/questions/65844043/moving-a-gmp-number 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…