ARM Technical Support Knowledge Articles

POINTER ARITHMETIC DELIVERS UNEXPECTED RESULTS

Applies to: C251 C Compiler

Answer


Information in this article applies to:


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

ATTACHED FILES

Request the files attached to this knowledgebase article.

Article last edited on: 2007-12-18 00:45:39

Rate this article

[Bad]
|
|
[Good]
Disagree? Move your mouse over the bar and click

Did you find this article helpful? Yes No

How can we improve this article?

Link to this article
Copyright © 2011 ARM Limited. All rights reserved. External (Open), Non-Confidential