I’ve been having trouble for hours now while trying to compare 2 seemingly identical structs. I’ve looked into alignment and padding as possible issues but found no issues. When I played around with different combinations of designated initialisation and zero initialisation combined with strcpy()
I found that memcpy()
returned either 1
or 0
. I hope I’ve finally narrowed down the problem into a single C file.
name = my-lib
version = 1.2.3.4.5
name = my-lib
version = 1.2.3.4.5
FAILED (res1) memcmp() = 1
FAILED (res2) memcmp() = 1
PASSED (res3)
is the output of;
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#define DRIVERS_NAME_BUFF_SIZE 64
#define DRIVERS_VERSION_BUFF_SIZE 64
typedef const struct drivers {
char name[DRIVERS_NAME_BUFF_SIZE];
char version[DRIVERS_VERSION_BUFF_SIZE];
} const drivers;
void print_drivers(drivers drvers) {
printf("name = %sn", drvers.name);
printf("version = %sn", drvers.version);
}
int main() {
drivers before = {
.name = "my-lib",
.version = "1.2.3.4.5"
};
drivers after = {0};
strcpy(after.name, "my-lib");
strcpy(after.version, "1.2.3.4.5");
print_drivers(before);
print_drivers(after);
printf("n");
/****************
* res1
***************/
int res1 = memcmp((uint8_t *)(&before), (uint8_t *)(&after), sizeof(drivers));
if (res1 != 0) {
printf("FAILED (res1) memcmp() = %dn", res1);
} else {
printf("PASSED (res1)n");
}
/****************
* res2
***************/
int res2 = memcmp(&before, &after, sizeof(drivers));
if (res2 != 0) {
printf("FAILED (res2) memcmp() = %dn", res2);
} else {
printf("PASSED (res2)n");
}
/****************
* res3
***************/
uint8_t * base_before = &before;
uint8_t * base_after = &after;
int res3 = memcmp(base_before, base_after, sizeof(drivers));
if (res3 != 0) {
printf("FAILED (res3) memcmp() = %dn", res3);
} else {
printf("PASSED (res3)n");
}
}
I’ll quickly note that removing both const
s from the typedef
“fixes” the problem in that all memcmp()
s return 0. I don’t understand this, can someone please explain it to me. Thank you