Important Notice: Our web hosting provider recently started charging us for additional visits, which was unexpected. In response, we're seeking donations. Depending on the situation, we may explore different monetization options for our Community and Expert Contributors. It's crucial to provide more returns for their expertise and offer more Expert Validated Answers or AI Validated Answers. Learn more about our hosting issue here.

Programming 7 — What does “unaligned access” mean, and how can I fix it?

0
Posted

Programming 7 — What does “unaligned access” mean, and how can I fix it?

0

Unaligned accesses typically come up when programs use malloc(3) or other memory allocation routines in atypical ways, or when programs do certain (hazardous) kinds of type casts. malloc(3) returns data aligned to the most restrictive alignment (8 byte boundaries). If you are writing your own malloc wrapper (say to add a reference count) and you write code like this: char *mymalloc(int size) { short *newmem; newmem = (short *) malloc(size + sizeof(short)); *newmem = 1; /* initialize reference count */ return (char *) (newmem + 1); } you are then returning a pointer that is no longer 8-byte aligned. Now, code like: int *i; i = (int *) mymalloc(sizeof(int)); *i = 10; will generate unaligned access messages whenever *i is used. An example of dangerous casting would be something like: char buffer[100]; int i; i = (int)*((int *)&buffer[3]); The program will usually still run correctly, because an exception handler in the kernel performs an unaligned read. There are some rare cases, howe

What is your question?

*Sadly, we had to bring back ads too. Hopefully more targeted.

Experts123