gmp_printf and mingw for stdint format macros
Emmanuel.Thome at inria.fr
Thu Jan 8 13:42:27 UTC 2015
I've come across a bug, while porting some software to mingw. Mingw
has an obsolete gmp-5.1.2 package, but I expect the behaviour would be
identical with gmp-6.0.0.
The following code crashes with a segfault:
uint64_t a = 42;
mpz_init_set_str(b, "17", 0);
gmp_printf("%" PRIu64" %Zd\n", a, b); /* SEGV */
(compiled with gcc-4.8.1, with -std=c99)
The reason is along the following lines. PRIu64 gets substituted to the
microsoft-specific "I64u". This is undefined behaviour in ISO C.
gmp_printf is not aware of this specificity, and steps over this
unrecognized "%I64u" silently (line 600 in doprnt.c, since the ASSERT(0)
expands to nothing). It then tries to print as an mpz the next non-format
argument it finds. Since a hasn't been consumed by a recognized format
specifier at this point, mpz_get_str is attempted with a instead of b.
Bang, you're dead.
It's not clear to me whether there is something to change, and what.
Maybe allowing gmp_printf("%" PRIu64" %Zd\n", a, b) to work correctly
would be a reasonable goal, although this would mean special-casing the
mingw platform. This sort of fix may also be more appropriate as specific
to the mingw package itself.
More information about the gmp-bugs