CLearner
CLearner

Reputation: 542

C++ mpir : How to initialize mpz_t array?

Source:

//$ DO DECLARATION
#define VEC_MAX_SIZE 600000
mpz_t Vec[ VEC_MAX_SIZE ];

//$ DO INITIALIZATION
mpz_array_init( Vec[ 0 ], VEC_MAX_SIZE, 2000 ); // Stack overflow error - 3rd param

Problem:

The problem is that I don't know how to properly initialize an mpz_t array, which in this case is Vec. The error is stack overflow. I think it is caused by the 3rd parameter. Here is the protype/definition of mpz_array_init:

#define mpz_array_init __gmpz_array_init
__GMP_DECLSPEC void mpz_array_init __GMP_PROTO ((mpz_ptr, mp_size_t, mp_size_t));

Error:

Unhandled exception at 0x008e8377 in TestMPIR.exe: 0xC00000FD: Stack overflow.

Note:

I am using mpir 3.1.1 on Windows 7 64 Bit.

This one from mpir's example works fine:

mpz_t Vec[ 20000 ];
mpz_array_init( Vec[ 0 ], 20000, 512 );

ANSWER:

Thanks to @Zeta for his/her awesome answer. Correct me if I am wrong. I just want to post this here so other newbies can learn from it.

#define MAX_VEC_SIZE 600000

malloc method (should be for C style I guess):

mpz_t *Vec;

if( ( Vec = ( mpz_t *)::malloc( sizeof( mpz_t ) * MAX_VEC_SIZE ) ) == 0 ) {
    ::perror( "Out of memory" );
    return false;
}

//> Initialize Vec loop ( ... )

::free( Vec );

C++ style?

mpz_t *VecEx = new mpz_t[ MAX_VEC_SIZE ];

//> Initialize VecEx loop ( ... )

delete [ ] VecEx;

This answer is based on @Zeta's answer (the accepted answer).

Upvotes: 2

Views: 2591

Answers (1)

Zeta
Zeta

Reputation: 105876

There's simply not enough space on the stack for such a large vector ("stack overflow"). You have to allocate it dynamically:

mpz_t * Vec = malloc(VEC_MAX_SIZE * sizeof(mpz_t));

Vec is roughly 6MiB in size. The stack isn't big enough for such objects. Note that GMP also provides a C++ interface.

Upvotes: 5

Related Questions