-6

can anyone help me what does this line of code do:

((struct mac_tb_ind *) (tb_p->data))->first_bit = 0; 

the structs are defined below:(tb_p is of kind of mem_block_t)

struct mac_tb_ind {
    unsigned char  *data_ptr;
    unsigned short  size;
    unsigned char   error_indication;
    unsigned char   first_bit;
};

typedef struct mem_block_t {
    struct mem_block_t *next;
    struct mem_block_t *previous;
    unsigned char       pool_id;
    unsigned char      *data;
} mem_block_t;
shahriar
  • 49
  • 4
  • the member tb_p->data is in fact a struct mac_tb_ind pointer, set the field first_bit of this to 0. – dgsomerton Mar 22 '18 at 07:08
  • 3
  • @AnttiHaapala But why? I can't conclude from just a valid cast. – llllllllll Mar 22 '18 at 07:15
  • The line of code is there to invoke undefined behavior bugs. https://stackoverflow.com/questions/98650/what-is-the-strict-aliasing-rule – Lundin Mar 22 '18 at 07:34
  • 1
    @Lundin I think the `unsigned char*` is used as a `void*` here. No UB here unless the provider of `data` puts a wrong pointer. And even if the `data` pointer is wrong, the UB should be caused by alignment issue, not strict aliasing. To be honest, I found the accepted answer in your link very misleading. See [this](https://stackoverflow.com/questions/49339571/undefined-behavior-from-pointer-math-on-a-c-array/49339771?noredirect=1#comment85698063_49339771) post, one of the answerer and I are misled by it. Turns out the `-strict-aliasing` flag is talking about a totally different thing. – llllllllll Mar 22 '18 at 07:55
  • @liliscent If `data` always points to a `struct mac_tb_ind`, then it should be declared as such. The only reason why someone wouldn't do that, is because they are confused. I'm not sure what you mean with "wrong pointer", what's relevant for strict aliasing is the effective type of the pointed-at data, nothing else. Of course it can be misaligned too, that's another story. – Lundin Mar 22 '18 at 08:00

1 Answers1

1

tb_p->data the pointer stored in data.

(struct mac_tb_ind *) (tb_p->data) typecasts the pointer so the compiler knows how to interpret it

((struct mac_tb_ind *) (tb_p->data))->first_bit = 0; the value stored in first_bit is set to 0

Theo Walton
  • 1,085
  • 9
  • 24
  • And when you're wrong, and told the compiler to use the wrong datatype with the cast, Wake me up, before you go-go. – user4581301 Mar 22 '18 at 07:51