What is the range of illegle memory addresses?

Xi Ruoyao xry111@mengyan1223.wang
Wed May 19 06:13:23 GMT 2021


On Tue, 2021-05-18 at 19:21 -0500, Segher Boessenkool wrote:
> On Tue, May 18, 2021 at 04:46:13PM -0500, Peter Bergner via Gcc-help
> wrote:
> > On 5/18/21 4:35 PM, Peng Yu wrote:
> > > So, to write a portable C program, no values other than NULL
> > > should be
> > > used as an invalid memory address?
> > 
> > I guess it depends on your definition of invalid.  NULL may be a
> > special
> > address used as a sentinel, but that doesn't mean every system will
> > give
> > you a SEGV if you happen to access NULL.  Some will happily let you
> > do it.
> 
> You can also use the address of an actual object for this.  This is
> standard for sentinel structs even: every pointer in a sentinel object
> points to some (other or same) sentinel object, so that you can always
> dereference without having to check for NULL first.  No non-sentinel
> object will have the same address, so this works fine.
> 
> The only thing special about the address 0 is that it is cheaper to
> test for than most other numbers, on most architectures.

And there is some (very rarely) conditions where NULL can't be used as a
sentinel and another value is used.  For example, mmap() returns
MAP_FAILED (it's value is (void *) -1) on failure.  NULL can't be used
here because (on some platform) it's perfectly legal to set a memory
mapping on page 0.
-- 
Xi Ruoyao <xry111@mengyan1223.wang>
School of Aerospace Science and Technology, Xidian University



More information about the Gcc-help mailing list