简体   繁体   中英

Custom memcmp() of a struct with char member

I've written the following C code to compare two areas of memory and check if they are identical

#include <stdio.h>

struct s1 {

   int a, b;
   char c;

} s1;


int memcmpwannabe(void* value1, void *value2, int size1, int size2) {

   if(size1 != size2)
      return -1;

   if(size1 == 0 || size2 == 0)
      return -1;

   //memcmp() wannabe
   char *p1 = value1;
   char *p2 = value2;
   int sz = size1;

   do {
       if(*p1 != *p2)
           break;
       else
           p1++, p2++;
   }
   while(--sz != 0);

   if(sz == 0)
      return 0;

   return -1;

}


int main() {

   struct s1 v1;
   struct s1 v2;

   v1.a = 1;
   v1.b = 2;
   v1.c = 'a';

   v2.a = 1;
   v2.b = 2;
   v2.c = 'a';

   int res = memcmpwannabe((void*) &v1, (void*) &v2, sizeof(s1), sizeof(s1));

   printf("Res: %d\n", res);

}

The structures are identical, but it will return -1 anyway. After some debugging i found that the 3 padding bytes after the char variable are filled with random data, not with zeroes as i was expecting.

Knowing this and the fact that i want to keep it as generic as possible (so using void* as arguments), can somebody point me to an alternative byte to byte comparison?

(Before somebody asks, i'm writing a custom memcmp() because in some implementations it will continue after a difference

Knowing this and the fact that i want to keep it as generic as possible ( so using void* as arguments )

If you only take void * pointers, by definition you know nothing about the internal organization of the objects. Which means you know nothing about the meaning of the bytes (which are in "real" members and which are in hidden, padding-only members).

I would say this is not something that you can easily do with standard C.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM