I have a function where I’m trying to take a 16-bit from a large chunk of data. I’m running this code on a Solaris box and I can compile without warning or error. When I run this code, however, whenever it gets to the part where I de-deference my pointer, I instantly get a bus error. The code looks something like:
void find_info(unsigned char* packet) {
int offset = 9;
uint16_t short_value = *(uint16_t*)(packet+offset);
}
The bus error occurs when I’m trying to de-reference that “packet+offset” pointer in order to get a short. I know for a fact there is data at packet[offset] and packet[offset+1]. On Linux and Cygwin this code works fine. As far as I know, I’m not doing anything revolutionary. What’s going on here?
Sounds like an alignment problem. On the Sun SPARC processor, you can only access something like a short via a pointer that is divisible by some power of 2, typically 8. So the value of offset=9 is clearly going to cause a problem.
See http://blogs.oracle.com/d/entry/on_misaligned_memory_accesses for more details.
I can’t recommend any way of fixing this without seeing more context; but if you’re reading data from some input source, you could just read the bytes and convert to a short using ntohs (see the man page for ntohs for details).