2015-01-09 58 views
0

好的,試圖讀取兩個可變大小的mpz_t。文件格式:gmp_import分段錯誤

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

有誰知道這是爲什麼分手?

+0

告訴我們你是怎麼稱呼'read_key()' – Gopi

+0

'read_key(f,k);'(https://github.com/phyrrus9/RSA3/blob/master/crypto.c#L7) – phyrrus9

回答

0

據我可以告訴

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

你不回你剛創建的指針的地址,所以k個指針沒有任何東西

+0

非常好點。讓我改變那個。上帝我討厭這個編譯器沒有警告我那個。 – phyrrus9

+0

好,讓我們看看是否修復它 –

+0

那,並改變導入行到'mpz_import(k->指數,1,1,1,1,0)'固定它。不能相信我錯過了這一點。謝謝。 – phyrrus9