c++ - Segmentation fault (core dumped) while using GMP Integers -


i wrote simple program in c++, using gmp library, prints out modulus of numbers which's digits composed of 1 (like 1, 11, 111, 1111, 11111, ...) , 2001; problem when program reaches 23 digits of 1, error saying segmantation fault(core dumped). can point out problem ? here code :

#include <iostream> #include <stdio.h> #include <string> #include <gmpxx.h>  int main(int argc, char** args){      mpz_t currnumber;     mpz_init(currnumber);        mpz_set_str(currnumber, "1", 10);      while(mpz_sizeinbase(currnumber, 10) < 24){         char* digits =  mpz_get_str(nullptr, 10, currnumber);         strcat(digits, "1");         mpz_set_str(currnumber, digits, 10);         digits = nullptr;           mpz_t r;         mpz_init(r);             mpz_set_str(r, "1", 20);          mpz_t divisor;         mpz_init(divisor);           mpz_set_str(divisor, "2001", 20);           mpz_mmod(r, currnumber, divisor);          std::cout << "====>" << currnumber << " mod(2001) = " << r << "\n\n\n";          //clean         mpz_clear(r);         mpz_clear(divisor);          }      std::cout << "went until " << mpz_sizeinbase(currnumber, 10) << " digits !" << "\n";      ///clean     mpz_clear(currnumber);      return 0; } 

first obvious bug is:

    char* digits =  mpz_get_str(nullptr, 10, currnumber);     strcat(digits, "1"); 

the buffer allocated mpz_get_str not reliably have room concatenate 1 character onto contents.

i think use:

    char* digits =  mpz_get_str(nullptr, 10, currnumber);     std::string more_digits = std::string(digits) + "1";     free(digits);     mpz_set_str(currnumber, more_digits.c_str(), 10); 

1) since in c++, should use std::string string operations , don't need learn obscurities of working c strings.
2) if understand mpz_get_str correctly (despite never having used myself) need free buffer allocated (as did in suggested code) avoid memory leak.


Comments

Popular posts from this blog

javascript - Karma not able to start PhantomJS on Windows - Error: spawn UNKNOWN -

Nuget pack csproj using nuspec -

c# - Display ASPX Popup control in RowDeleteing Event (ASPX Gridview) -