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, 1095👍, 0💬
Popular Posts:
What print out will the folloging code produce? main() { char *p1=“name”; char *p2; p2=(char*)malloc...
What is NullPointerException and how to handle it? When an object is not initialized, the default va...
Which bit wise operator is suitable for turning off a particular bit in a number? The bitwise AND op...
Can you explain in brief how the ASP.NET authentication process works? ASP.NET does not run by itsel...
What Happens If a Hyper Link Points to a Music File? - XHTML 1.0 Tutorials - Understanding Hyper Lin...