gmp_import 分段错误

gmp_import segmentation fault

好的,尝试读取两个 mpz_t 的可变大小。文件格式:

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)

及其进入的结构:

struct kbag
{
    mpz_t modulo;
    mpz_t exponent;
};

以及读取它的代码:

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);
}

另外,kbag 结构初始化如下:

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

是的,它已在传递给 read_key()

的 k 上被调用

回溯:

30 mpz_import(k->模数, 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

完整源代码:https://github.com/phyrrus9/RSA3

有人知道为什么会这样吗?

据我所知

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

但在

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

你没有return你刚创建的指针的地址,所以 k 指针没有指向任何东西