Search code examples
clinuxsegmentation-faultgmp

Segmentation fault (core dumped) in C (with GMP lib)


I declare mpz variables and initialise them in a void function.

It's not working.

For example:

mpz_t a;
init();
   ...
void init(){
   mpz_init(a);
   ....
 }

No error.

 init();
     ...
    void init(){
      mpz_t a;
      mpz_init(a);
    }

An error occurs.


Solution

  • From the little bit of code you have, the difference seems to be the scope of the variable a. What is the point of calling mpz_init(a) on a variable with only local scope (within your init() function)? After init() returns, a disappears. If you need it for anything else later, the variable a, and presumably some of the side effects from mpz_init(), won't exist. If you want the side effects of mpz_init() to persist past the end of init(), it must take effect on some structure that also persists past the end of init(). In your first example, a is declared with global scope, so it persists for the entirety of your program.