Note that there are some explanatory texts on larger screens.

plurals
  1. POWeird bug in c implementing schoolbook multiplication using gmp
    primarykey
    data
    text
    <p>I have a weird problem.</p> <p>I am trying to implement the schoolbook multiplication. I am aware that the function mpz_mul does that for me but it is my task to implement it myself as a homework.</p> <p>So here is my code:</p> <pre><code>void mpz_school_mul(mpz_t c, mpz_t a, mpz_t b) { size_t i; mp_limb_t b_i; mpz_t c_part; mpz_init(c_part); /* Backup a for the special case a := a * b. */ mpz_t a_backup; mpz_init(a_backup); mpz_set(a_backup, a); /* Clear the result */ mpz_set_ui(c,0); gmp_printf("i = %zx, size(b) = %zx, a = %Zx, b = %Zx\n", i, mpz_size(b), a, b); for(i = 0; i &lt; mpz_size(b); i++) { printf("test\n"); b_i = mpz_getlimbn(b,i); /* c = a*b_i*B^i + ... + a*b_0*B^0 */ /* Calculate a*b_i for every round. */ mpz_mul_limb(c_part,a_backup,b_i); /* Shift it to the right position (*B^i). */ mpz_mul_base(c_part,c_part,i); /* Sum all a*b_i*B^i */ mpz_school_add(c, c, c_part); } mpz_clear(a_backup); mpz_clear(c_part); } </code></pre> <p>This code works well for me and i can test it with several parameters. The result is correct so I don't think I need to change to much in the calculation part. ;)</p> <p>As example: This parameters work as intended.</p> <pre><code>mpz_set_str(a, "ffffffff00000000abcdabcd", 16); mpz_set_str(b, "cceaffcc00000000abcdabcd", 16); mpz_school_mul(c,a,b); </code></pre> <p>Now to the bug:</p> <p>When i run the program with a parameter b with a zero limb (I'm using a 32 bit VM) at the end the program crashes:</p> <pre><code>mpz_set_str(a, "ffffffff00000000abcdabcd", 16); mpz_set_str(b, "cceaffcc00000000", 16); mpz_school_mul(c,a,b); </code></pre> <p>The output with this parameter b_0 = 0 is:</p> <pre><code>i = 0, size(b) = 2, a = ffffffff00000000abcdabcd, b = cceaffcc00000000 </code></pre> <p>I think the for-loop stucks because the printf("test\n"); does not show up in this run.</p> <p>Thanks for your help ;)</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload