在 C 中打印结构

Printing a structure in C

我正在对 wireshark 源代码进行一些更改。在一个特定的时间点,我打印出一个名为 SSLDecoder 的结构,就像这样

FILE *f;  
f=fopen("file.txt","a+");
size_decoder=sizeof(SslDecoder);  
for(i=0; i < size_decoder; i++){
    fprintf(f,"%02x",*(ssl_session->client_new+i));
}
fprintf(f,"\n");

ssl_session 属于 struct SslDecryptSession 类型,定义为

typedef struct _SslDecryptSession {
    guchar _master_secret[SSL_MASTER_SECRET_LENGTH];
    guchar _session_id[256];
    guchar _client_random[32];
    guchar _server_random[32];
    StringInfo session_id;
    StringInfo session_ticket;
    StringInfo server_random;
    StringInfo client_random;
    StringInfo master_secret;
    StringInfo handshake_data;
    /* the data store for this StringInfo must be allocated explicitly with a capture lifetime scope */
    StringInfo pre_master_secret;
    guchar _server_data_for_iv[24];
    StringInfo server_data_for_iv;
    guchar _client_data_for_iv[24];
    StringInfo client_data_for_iv;

    gint state;
    SslCipherSuite cipher_suite;
    SslDecoder *server;
    SslDecoder *client;
    SslDecoder *server_new;
    SslDecoder *client_new;
    gcry_sexp_t private_key;
    StringInfo psk;
    guint16 version_netorder;
    StringInfo app_data_segment;
    SslSession session;
} SslDecryptSession;

SslDecoder 的类型是

typedef struct _SslDecoder {
    SslCipherSuite* cipher_suite;
    gint compression;
    guchar _mac_key_or_write_iv[48];
    StringInfo mac_key; /* for block and stream ciphers */
    StringInfo write_iv; /* for AEAD ciphers (at least GCM, CCM) */
    SSL_CIPHER_CTX evp;
    SslDecompress *decomp;
    guint32 seq;
    guint16 epoch;
    SslFlow *flow;
} SslDecoder;

但是,打印到文件的输出是不规则的。 pastebin

上的示例输出

有人可以告诉我我做错了什么吗?

我后来在文件中使用这个输出来填充另一个像这样的解码器(现在,由于不规则打印到文件,我面临段错误)

SslDecoder *temp_decoder;
c = malloc(sizeof(SslDecoder));

for (i=0; i<sizeof(SslDecoder); i++){
    fscanf(f,"%02x",&c[i]);
}
memcpy(temp_decoder,c, sizeof(SslDecoder));

当你进行指针运算时,指针偏移指向类型大小的倍数;它 将指针偏移指定的 字节数 。请记住,如果您有 T* p,则 *(p + i) 等同于 p[i].

在你的代码中,你做了:

size_decoder=sizeof(SslDecoder);  
for(i=0; i < size_decoder; i++){
    fprintf(f,"%02x",*(ssl_session->client_new+i));
}

*(ssl_session->client_new+i) 在每次迭代中将 client_new 指针偏移 i * sizeof (SslDecoder) 字节。

您打算在每次迭代中仅将指针前进一个字节,因此您必须对指向 char:

的指针执行指针运算
size_decoder=sizeof(SslDecoder);  
const unsigned char* p = (unsigned char*) ssl_session->client_new;
for(i=0; i < size_decoder; i++){
    fprintf(f,"%02x", p[i]);
}

你同样需要在读回文件时做类似的事情。我还应该指出,在您的阅读代码中:

SslDecoder *temp_decoder;
c = malloc(sizeof(SslDecoder));

for (i=0; i<sizeof(SslDecoder); i++){
    fscanf(f,"%02x",&c[i]);
}
memcpy(temp_decoder,c, sizeof(SslDecoder));

memcpy 调用不正确;您还没有为 temp_decoder 分配任何内存。您根本不需要使用 memcpy

SslDecoder *temp_decoder = malloc(sizeof *temp_decoder);
unsigned char* p = (unsigned char*) temp_decoder;
for (i=0; i<sizeof(SslDecoder); i++){
    int temp; // "%x" corresponds to an int type
    fscanf(f, "%02x", &temp);
    p[i] = (unsigned char) temp;
}