Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
239 views
in Technique[技术] by (71.8m points)

Moving a GMP number

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...