在这个函数中,我尝试检查char数组是否包含广播MAC地址。为此,我将每个数组元素与0xFF进行比较。
static inline bool recibir_trama_l2_en_interface(interface_t *interface, cab_ethernet_t *cab_ethernet) {
char *mac = MAC_IF(interface);
if(IF_EN_MODO_L3(interface)) {
char *mac_destino = cab_ethernet->mac_destino.dir_mac;
mostrar_dir_mac(&interface->prop_intf->dir_mac);
mostrar_dir_mac(&cab_ethernet->mac_destino);
bool bandera_prueba = true;
bandera_prueba = mac_destino[0] == 0xFF;
if(mac_destino[0] == 0xFF && mac_destino[1] == 0xFF && mac_destino[2] == 0xFF && mac_destino[3] == 0xFF && mac_destino[4] == 0xFF && mac_destino[5] == 0xFF) {
printf("Esto está pasando.\n");
}
printf("AABBNINKD.\n");
if(mac_destino[0] == 0xFF) {
printf("Esto sí pasa.\n");
}
}
return false;
}这些是我正在使用的结构。
typedef struct cab_ethernet_ {
dir_mac_t mac_destino;
dir_mac_t mac_origen;
short tipo;
char payload[TAM_MAX_PAYLOAD];
unsigned int FCS;
} cab_ethernet_t;
typedef struct dir_mac_ {
char dir_mac[TAM_DIR_MAC];
} dir_mac_t;调试器显示mac_destino[0]的内容是0xFF。但是您还可以看到,在比较之后,bandera_prueba被设置为false。

另一件正在发生的事情是,显然程序正在跳过这些指令。
if(mac_destino[0] == 0xFF && mac_destino[1] == 0xFF && mac_destino[2] == 0xFF && mac_destino[3] == 0xFF && mac_destino[4] == 0xFF && mac_destino[5] == 0xFF) {
printf("Esto está pasando.\n");
}
if(mac_destino[0] == 0xFF) {
printf("Esto sí pasa.\n");
}我的意思是,调试器从78行跳到83行,再跳到89行。

导致这些错误的是这种比较有什么问题吗?
发布于 2021-11-13 10:31:30
常量0xFF的值为255。在您的C实现中,char是带符号的,并且只能具有从−128到+127的值。mac_destino[0]是一个char。因此,mac_destino[0] == 0xFF永远不可能是真的。单步执行调试器中的代码似乎会跳过行,因为编译器已对程序进行了优化,以省略不可能的部分。
要解决此问题,请将类型更改为unsigned char。
优选地,将struct dir_mac_中dir_mac的元素类型改为unsigned char,将mac_destino的类型改为unsigned char *。如果无法做到这一点,请将mac_destino的定义从char *mac_destino = cab_ethernet->mac_destino.dir_mac;更改为unsigned char *mac_destino = (unsigned char *) cab_ethernet->mac_destino.dir_mac;。
如果您无法做到这一点,您可以在每个比较中插入一个转换,例如将mac_destino[0] == 0xFF更改为(unsigned char) mac_destino[0] == 0xFF。
https://stackoverflow.com/questions/69951375
复制相似问题