Categories:
.NET (357)
C (330)
C++ (183)
CSS (84)
DBA (2)
General (7)
HTML (4)
Java (574)
JavaScript (106)
JSP (66)
Oracle (114)
Perl (46)
Perl (1)
PHP (1)
PL/SQL (1)
RSS (51)
Software QA (13)
SQL Server (1)
Windows (1)
XHTML (173)
Other Resources:
I have got some code that is trying to unpack external structures
I've got some code that's trying to unpack external structures, but it's crashing with a message about an ``unaligned access.'' What does this mean? The code looks like this:
struct mystruct {
char c;
long int i32;
int i16;
} s;
char buf[7], *p;
fread(buf, 7, 1, fp);
p = buf;
s.c = *p++;
s.i32 = *(long int *)p;
p += 4;
s.i16 = *(int *)p;
✍: Guest
The problem is that you're playing too fast and loose with your pointers. Some machines require that data values be stored at appropriately aligned addresses. For instance, two-byte short ints might be constrained to sit at even addresses, and four-byte long ints at multiples of four.By converting a char * (which can point to any byte) to an int * or long int *, and then indirecting on it, you can end up asking the processor to fetch a multibyte value from an unaligned address, which it isn't willing to do.
A better way to unpack external structures is with code like
unsigned char *p = buf;
s.c = *p++;
s.i32 = (long)*p++ << 24;
s.i32 |= (long)*p++ << 16;
s.i32 |= (unsigned)(*p++ << 8);
s.i32 |= *p++;
s.i16 = *p++ << 8;
s.i16 |= *p++;
This code also gives you control over byte order. (This example, though, assumes that a char is 8 bits, and that the long int and int being unpacked from the ``external structure'' are 32 and 16 bits, respectively.)
2015-05-20, 1146👍, 0💬
Popular Posts:
Describe in detail Basic of SAO architecture of Remoting? For these types of questions interviewer e...
What is the difference between RegisterClientScriptBloc kand RegisterStartupScript? RegisterClientSc...
How do we host a WCF service in IIS? Note: - The best to know how to host a WCF in IIS is by doing a...
How To Run Stored Procedures in Debug Mode? - Oracle DBA FAQ - Introduction to Oracle SQL Developer ...
How Many Tags Are Defined in HTML 4.01? There are 77 tags defined in HTML 4.01: a abbr acronym addre...