Search code examples
c++gmp

Run C++ program with GMP library to use big numbers cause an error: C4146: unary minus operator applied to unsigned type, result still unsigned


I'm trying to use this library for a program of big primes.

I had installed GMP and had set a compiler: Microsoft Visual Studio Community 2019

I'm just trying to generate prime numbers:

#include <gmp.h>
int main() {
    gmp_randstate_t state;  // variable state for gmp_randinit, must be initialized 
    mpz_t p, q, N;
    mp_bitcnt_t n;  // number of bits for the number in range 0 to (2^n)-1, inclusive.

    n = 10;
    gmp_randinit_default(state);    // Initialize state with a default algorithm.

    while (true)
    {
        mpz_urandomb(p, state, n);  // Generate a uniformly distributed random integer
        if (mpz_probab_prime_p(p, 50) == 2) // Determine whether p is prime. Return 2 if p is definitely prime
            break;
    }
    while (true)
    {
        mpz_urandomb(q, state, n);  // Generate a uniformly distributed random integer
        if (mpz_probab_prime_p(q, 50) == 2) // Determine whether q is prime. Return 2 if q is definitely prime
            break;
    }

    return 0;
}

When I try to run via Visual Studio, I'm getting an error:

C4146: unary minus operator applied to unsigned type, result still unsigned 

at the file gmp.h line 2230

When I try to run via WSL 2, Ubuntu with the following:

g++ filename.cpp -lgmpxx -lgmp

./a.out

I get this output: Segmentation fault

I don't understand why is that.

Thanks.


Solution

  • The C4146 warning is just a bit of Microsoft nonsense. Look it up to understand it, then ignore it. Perfectly correct programs can emit this warning.

    The real error in your code (and the cause of the seqmentation fault) is that with GMP mpz_t variables must be initialised before use (and destroyed after use).

    mpz_t p, q, N;
    mpz_init(p);
    mpz_init(q);
    mpz_init(N);
    
    ...
    
    mpz_clear(p);
    mpz_clear(q);
    mpz_clear(N);
    

    GMP is a C library not a C++ one, so this kind of manual initialisation is needed.

    The GMP manual is pretty good, you should take a look.