Main problem with checking whether a pointer is in specific range is unfortunately the C standard itself. Pointer arithmetic has a defined behaviour only if performed on pointers of the same type within the memory range of the same object (i.e. within the same allocated array range). A the comparison operators are defined as arithmetic operations, this restriction apply to them as well. A workaround for this problem would be casting the pointers to the uintptr_t
type defined in stdint.h
, which is an integer type guaranteed to hold a pointer value. And then perform your comparisons.
Now to the part of obtaining the right boundaries. Typically a C project would contain some kind of linker script defining memory regions of the specific architecture. Commonly it will include lines similar to the following:
MEMORY
{
FLASH (rx) : ORIGIN = 0x00000000, LENGTH = 0x40000
SRAM (rwx) : ORIGIN = 0x20000000, LENGTH = 0x8000
}
then, in the same script the following definitions can be added:
_flash_start = ORIGIN(FLASH);
_flash_end = ORIGIN(FLASH) + LENGTH(FLASH);
And then in C code these symbols can be accessed using:
extern int _flash_start ;
extern int _flash_end;
And then a tricky part: The address of _flash_start
will correspond to the flash starting address, and the address of _flash_end
will correspond to the flash end address. I.e. the &_flash_start
and &_flash_end
are giving you the desired range.