c - Memcmp 用于两个具有不同数据的指针

标签 c debugging struct encoding memcmp

这个问题有点难以解释,因为代码片段是一个更大项目的一部分。我会尽我所能解释这个问题。

我有两个文件

    FILE *f,*m;
    f=fopen("/home/machine/decoder.txt","a+");
    m=fopen("/home/machine/offset.txt","a+");

在我运行以下代码的函数中,

    char *c;
    int i=0;
    c = malloc(sizeof(SslDecoder));

    //Pick a value from "decoder" file and compare it to a variable in the function

    while (fgets(c, sizeof(SslDecoder), f) != NULL) {

    //Print its value to offset file         
    fprintf(m,"%s\n",c);

    // Print value of another variable to offset file. 

    for(i=0;i<32;i++){
    fprintf(m,"%02x",ssl->client_random.data[i]);
    }
    fprintf(m,"\n");

    //Compare the memory in the pointers. 
    int check = memcmp(c,ssl->client_random.data,32);
    fprintf(m,"MEMCMP value: %d\n",check);
    }

offset.txt中打印的值如下

625b70a9659b2fe9ba76ea26d3cfb6126bae4a48b4997548b26d9a101e682bc3

625b70a9659b2fe9ba76ea26d3cfb6126bae4a48b4997548b26d9a101e682bc3
MEMCMP value: -44

client_random和ssl的定义如下-

        typedef struct _StringInfo {
        guchar  *data;      /* Backing storage which may be larger than data_len */
        guint    data_len;  /* Length of the meaningful part of data */
         } StringInfo;


        typedef struct _SslDecryptSession {
        StringInfo server_random;
        StringInfo client_random;
        StringInfo master_secret;
        guchar _client_data_for_iv[24];
        StringInfo client_data_for_iv;  
        gint state;
        SslCipherSuite cipher_suite;
        SslDecoder *server;
        SslDecoder *client;
        SslSession session;

    } SslDecryptSession;

我不明白为什么 memcmp 的值不为零。我怀疑存储在指针中的数据编码不同,但在这种情况下我该如何比较这些值。我不知道这两个指针中的数据是十六进制类型还是原始/ascii 数据。

最佳答案

您在 /home/machine/decoder.txt 中读取的数据是一个 ASCII 字符串。

您将其打印为 ASCII(使用 %s)。

您正在比较的数据是二进制数据(您正在打印的是 %02x,使用 %s 打印将打印垃圾,具体取决于数据是 ASCII或不)

所以他们当然不相等。

要比较它们,您必须将二进制值转换为 ASCII 或将 ASCII 转换为二进制。做出你的选择。比较两个字符串:

char sslstr[65];
for(i=0;i<32;i++){
  sprintf(sslstr+i*2,"%02x",ssl->client_random.data[i]);
}

int check = memcmp(c,sslstr,64);

旁白:您在太小的缓冲区上读取文本文件,您应该以零终止它,否则打​​印时字符串末尾会出现垃圾。

关于c - Memcmp 用于两个具有不同数据的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40474693/

相关文章:

比较 C 函数中的三个 float

我可以在解释这段代码时得到一些帮助吗?

javascript - 堆栈跟踪中的 node.js 文件位于何处?

debugging - 如何在 tvOS 中使用 _whyIsThisViewNotFocusable?

dictionary - 如何使用 GO 构建结构图并向其附加值?

c - 运行结构体中定义的函数

c - 如何使用命令参数?

ios - 调用协议(protocol)的 mutating 函数生成 "has no member ' functionName'"错误

java - Eclipse 调试器不会显示共享区域

C: 变量有初始值设定项但类型不完整