Search code examples
cimportsegmentation-faultgmp

gmp_import segmentation fault


Okay, trying to read in two mpz_t's of variable size. File format:

MODULO SIZE [l1] (8 bytes, big endian, measured in bytes)
EXPONENT SIZE [l2] (8 bytes, big endian, measured in bytes)
MODULO DATA (l1 bytes, little endian)
EXPONENT DATA (l2 bytes, little endian)

and the structure it goes into:

struct kbag
{
    mpz_t modulo;
    mpz_t exponent;
};

and the code to read it:

void read_key(FILE *f, struct kbag *k)
{
    unsigned long l1, l2;
    void *buf;
    int i;
    fread(&l1, sizeof(unsigned long), 1, f);
    fread(&l2, sizeof(unsigned long), 1, f);
    l1 = ntohl(l1);
    l2 = ntohl(l2);
    buf = malloc(l1);
    fread(buf, l1, 1, f);
    for (i = 0; i < l1; i++) printf("%02x ", *(char *)(buf +i));
    printf("\n");
    /* everything up to this point checks out 100% good (from the file) */
    mpz_import(k->modulo, l1, 1, 1, 1, 0, buf); //<-- segmentation fault here
    free(buf);
    for (i = 0; i < l2; i++) printf("%02x ", *(char *)(buf + i));
    printf("\n");
    buf = malloc(l2);
    mpz_import(k->exponent, l2, 1, 1, 1, 0, buf);
}

also, the kbag struct is initialized with the following:

struct kbag *init_kbag()
{
    struct kbag *k = malloc(sizeof(struct kbag));
    mpz_init(k->exponent);
    mpz_init(k->modulo);
}

and yes, it has been called on the k passed into read_key()

backtrace:

30 mpz_import(k->modulo, l1, 1, 1, 1, 0, buf); (gdb)

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff783035d in realloc () from /lib/x86_64-linux-gnu/libc.so.6
(gdb) back
#0  0x00007ffff783035d in realloc () from /lib/x86_64-linux-gnu/libc.so.6
#1  0x00007ffff7b748fc in __gmp_default_reallocate () from /usr/lib/x86_64-linux-gnu/libgmp.so.10
#2  0x00007ffff7b8a94a in __gmpz_realloc () from /usr/lib/x86_64-linux-gnu/libgmp.so.10
#3  0x00007ffff7b848d1 in __gmpz_import () from /usr/lib/x86_64-linux-gnu/libgmp.so.10
#4  0x0000000000400b9a in read_key (f=0x603010, k=0x6032a0) at rsalib.c:30
#5  0x00000000004009b3 in main (argc=2, argv=0x7fffffffe278) at crypto.c:7

Full source code: https://github.com/phyrrus9/RSA3

does anybody know why this is breaking?


Solution

  • as far as I can tell

    struct kbag *k = init_kbag(); //line 6 crypto.c
    

    but in

    struct kbag *init_kbag()
    {
    struct kbag *k = malloc(sizeof(struct kbag));
    mpz_init(k->exponent);
    mpz_init(k->modulo);
    }
    

    you don't return the address of the pointer you just created, so the k pointer isn't pointing to anything