4

Architecture ARM9. Programming Language C.

We have a third-party stack and one of the calls takes a pointer(pBuffer) to a memory location. Within the stack, they are free to move around the pointer passed and access it as they wish. Unfortunately, they offset the passed in pointer and passed it into a another function that tried to do this from an odd/unalighed memory location

         ((uint16 *)pBuffer)[index] = value;

where value is of type uint16 and index is bounds checked and indexes pBuffer. This causes a unaligned memory access exception. pBuffer points to char * on the heap.

As mentioned, even though we can peek into the third-party stack, we can not update the code officially. So we notify the provider and they provide the update in the next release.

I want to understand if there is a work around for this. How do I perform the above assignment without violating the unaligned access? What is the best approach to resolving such problems.

4

3 回答 3

7

Copy the value byte by byte. Cast it to a (unsigned) char pointer, and then copy a byte at a time.

It's not pretty, but it doesn't sound like you have many options.

于 2009-03-23T15:59:19.600 回答
1

There are three possibilities, and I cannot determine from your question so far which is the case.

Case 1: The index is always odd. Solution: memmove() pBuffer over 1 bytes Case 2: The index is sometimes odd, and you can predict up front when it will be. Solution: memmove() pBuffer over 1 byte when you know index will be odd. Case 3: The index is sometimes odd, and you cannot predict when it will be. This is unfortunate, because the code will fault.

于 2009-03-23T16:06:42.953 回答
1

If you are in control of pBuffer, as a work around, you could declare it as an array of uint32_t (or whatever matches the alignment of your architecture). With declaring the buffer as uint32_t, the compiler will choose the correct alignment. You can cast it to uint8_t* when calling your target function.

This should work with the example code you posted, but may still fail if the third party code applies any unaligned offset to the buffer.

于 2018-04-23T07:58:25.300 回答