Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a buffer of char* with intermediate casting to int*

I could not fully understand the consequences of what I read here: Casting an int pointer to a char ptr and vice versa

In short, would this work?

set4Bytes(unsigned char* buffer) {
  const uint32_t MASK = 0xffffffff;
  if ((uintmax_t)buffer % 4) {//misaligned
     for (int i = 0; i < 4; i++) {
       buffer[i] = 0xff;
     } 
  } else {//4-byte alignment
    *((uint32_t*) buffer) = MASK;
  }

}

Edit
There was a long discussion (it was in the comments, which mysteriously got deleted) about what type the pointer should be casted to in order to check the alignment. The subject is now addressed here.

like image 669
Antonio Avatar asked Sep 23 '14 11:09

Antonio


1 Answers

This conversion is safe if you are filling same value in all 4 bytes. If byte order matters then this conversion is not safe. Because when you use integer to fill 4 Bytes at a time it will fill 4 Bytes but order depends on the endianness.

like image 82
Hemant Gangwar Avatar answered Oct 02 '22 23:10

Hemant Gangwar