添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I use this program to store a mpz value but when I add a 0 ( 400000000000000000000000000000000000000 instead of 40000000000000000000000000000000000000 -> 38 0s instead of 37) I get

free(): double free detected in tcache 2

Aborted (core dumped)

#include <iostream>
#include <gmpxx.h>
#include <vector>
using namespace std;
int main(const int argc, const char * const argv[])
char *str= (char*)malloc(sizeof(char)*1024);
mpz_class l;
l=40000000000000000000000000000000000000_mpz;
mpz_set_str(l.get_mpz_t(), str, 10);
cout<<endl<<str;
return 0;

Is there a possibility to store large numbers?

Thank you

How should I declare str? Only after I read the arguments I can find out how long the "message is". Is there a way to declare only a pointer? – user11903678 Aug 22, 2019 at 20:17 This is a common problem when working with C-style strings. If you don't know how big a message could be, you're usually best off assuming the worst case and allocating for the biggest possible message. Since this is now a statically-sized allocation, consider using an automatic variable. For example, consider using char str[1024]; in place of char *str= (char*)malloc(sizeof(char)*1024);. Fewer memory management headaches in the future. – user4581301 Aug 22, 2019 at 20:26

Your code has undefined behaviour because you are trying to assign l from an uninitialised array str.

I'm guessing you got your functions confused and meant to write the opposite

mpz_get_str(str, 10, l.get_mpz_t());

That code assigns l to str.

Use the following code to work out how big str needs to be

size_t size = mpz_sizeinbase(l.get_mpz_t(), 10) + 2;
                Here's an explanation for the + 2 part: "The right amount of allocation is normally two more than the value returned by mpz_sizeinbase, one extra for a minus sign and one for the null-terminator."
– Ted Lyngmo
                Aug 22, 2019 at 20:34
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.