This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

Compiler: check valid range of addresses C2000

Tool/software: TI C/C++ Compiler

Hi, 

according to c/c++ standards, comparison of two pointers of different structure is undefined.

from internet(:/):

"If two pointers p and q of the same type point to different objects that are not members of the same object or elements of the same array or to different functions, or if only one of them is null, the results of p<qp>qp<=q, and p>=q are unspecified."

i wonder what is a proper way of deciding if a pointer is falling between two absolute addresses? is the following code valid in C2000 compiler?

int* p;

p = (int*)(some value from a byte stream);

if ( p >= (int*)0x8000 && p<=(int*)0x9000)

{do something} 

thanks

regards

gzhang

  • This ...

    Leong said:

    int* p;

    p = (int*)(some value from a byte stream);

    if ( p >= (int*)0x8000 && p<=(int*)0x9000)

    {do something} 

    ... is undefined behavior. But that doesn't stop anyone else.  And it shouldn't stop you either.  The compiler will emit code which performs that comparison.  What happens next is what is undefined.  The compiler has no responsibility for that.  But you can take that responsibility on yourself.  

    Some tips to consider ...

    Be very verbose in your comments and documentation on this.

    You can share #define constants between C code and your linker command file.  It probably makes sense in this case.  Something like this would work ...

    /* addresses.h */
    #define RAM_BASE   0x8000
    #define RAM_LENGTH 0x1000

    Your C code can include that file and use those #define names.  Your linker command file can too ...

    #include "addresses.h"
    
    MEMORY
    {
       RAM : origin = RAM_BASE, length = RAM_LENGTH
       ...
    }

    Thanks and regards,

    -George

  • Thanks George.

    adding a guard in the header file is a good idea.

    i ended up casting the address instead to compare with the range. (unit_32)(p) .