Abhimanyu Khanna Abhimanyu Khanna - 6 months ago 37
C Question

Memcmp for two pointers with different data

This question is a bit hard to explain as the code snippet is part of a larger project. I will try to explain the problem to the best I can.

I have two files

FILE *f,*m;

In a function I run the following code,

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

// Print value of another variable to offset file.


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

The values printed in offset.txt are as follows


MEMCMP value: -44

Definition of client_random and ssl is as follows -

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;

I do not understand why the values of memcmp is not zero. I suspect that the data stored in the pointers are encoded differently, but how do I compare the values in that case. I do not know if the data is of hex type or raw/ascii data in either of the pointers.


The data that you're reading in /home/machine/decoder.txt is an ASCII string.

You're printing it as ASCII (using %s).

The data you're comparing with is binary data (you're printing is using %02x, printing it using %s will print garbage depending on data being ASCII or not)

So of course they're not equal.

To compare them, you have to convert the binary values to ASCII or ASCII to binary. Make your pick. To compare both strings:

char sslstr[65];

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

Aside: you're reading your text file on a buffer which is too small, and you should zero-terminate it or you'll have garbage at the end of the string when you print it.