When working with char buffers in C, sometimes it would be useful and more efficient to able to work with int-sized chunks of data at a time. To do this I can cast my char * to an int * and use that pointer instead. However I’m not entirely confident that this works the way I think it does.
For example, suppose I have char *data, does *(int32_t *)data = -1 always overwrite the bytes data[0], data[1], data[2] and data[3] and no other bytes?
Expanding on my comment.
There are two major issues here:
Violating strict-aliasing is technically undefined behavior. You are allowed to alias any datatype with
char*, but not the other way around.You can get around the issue with
f[no-]strict-aliasingon GCC.The other issue is alignment. The
charpointer might not be properly aligned. Accessing misaligned data may lead to performance degradation or even a hardware exception if the hardware doesn’t support misaligned access.If performance isn’t an issue, the full-proof way is to
memcpy()to anintarray buffer.Once these two issues are resolved, your example with:
overwriting
data[0],data[1],data[2], anddata[3]should work as expected ifsizeof(int32_t) == 4. Just pay attention to the endianness…