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, 1309👍, 0💬
Popular Posts:
What will be printed as the result of the operation below: main() { int x=20,y=35; x=y++ + x++; y= +...
How To Use "IN OUT" Parameter Properly? - Oracle DBA FAQ - Creating Your Own PL/SQL Procedures and F...
What are secure and non-secure websites? A secure Website uses the Secure Socket Layer (SSL) protoco...
Write an equivalent expression for x%8? x&7
How To Assign Debug Privileges to a User? - Oracle DBA FAQ - Introduction to Oracle SQL Developer In...