Keil Logo

C251: POINTER ARITHMETIC DELIVERS UNEXPECTED RESULTS


Information in this article applies to:

  • C251 Version 2 or higher

QUESTION

I have found a serious problem when I use pointer arithemetic with a generic memory allocation function. The results generated seem to consider only the 16-bit offset rather than the full address space of the 251 architecture (which is up to 16MB).

Example:

typedef unsigned char BYTE;
typedef unsigned long DWORD;

BYTE  *MemStart;                // first available memory location
BYTE  *GetLastAddress (void);   // returns last available memory location
DWORD freeSpace;

// this generates a incorrect result:
  freeSpace=(DWORD) GetLastAddress() - MemStart);   // generates incorrect result

ANSWER

A pointer subtraction delivers the number of elements within an array that is addressed by these pointers. By default the C251 uses far pointers. This implies that the pointers point to the same elements within a single 64KB segment.

To get the total memory that is between unrelated pointers (that point to any memory location) use a explicit cast to huge * as shown below:

  freeSpace=(DWORD)((BYTE huge *)GetLastAddress() - (BYTE huge *)MemStart);

Of course an cast to DWORD will work too and is maybe more transparent to understand:

  freeSpace= (DWORD)GetLastAddress() - (DWORD)MemStart;

MORE INFORMATION

SEE ALSO

Last Reviewed: Tuesday, December 18, 2007


Did this article provide the answer you needed?
 
Yes
No
Not Sure
 
  Arm logo
Important information

This site uses cookies to store information on your computer. By continuing to use our site, you consent to our cookies.

Change Settings

Privacy Policy Update

Arm’s Privacy Policy has been updated. By continuing to use our site, you consent to Arm’s Privacy Policy. Please review our Privacy Policy to learn more about our collection, use and transfers
of your data.