Does C have more macros like NULL?

Background:

When deleting a cell in a hash table using linear probing, you must indicate that one value existed in that cell, but may be missing during the lookup. The easiest way to solve this problem is to add another variable to store this information, but this additional variable can be avoided if the guaranteed invalid memory address is known and used to represent that state.

Question:

My guess is that since 0 is a guaranteed invalid memory address (most often), there must be more than just NULL. So my question is, doesn't C provide a standard macro for any other guaranteed invalid memory addresses?

+3


source to share


3 answers


Technically, NULL

it can't be invalid. It is guaranteed not to be the address of any object (C11 6.3.2.3:3):

An integer constant expression with a value of 0 or such an expression cast to type void * is called a null pointer constant (66). If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unevenly with a pointer to any object or function.

(66) Macro NULL is defined in (and other headers) as a null pointer constant

Your use does not require the value of the special address to be invalid: obviously, you do not access it unless segfaulting is part of the normal behavior of your program.



This way, you can use the addresses of as many objects as possible if the addresses of those objects are not intended for partial cell contents.

For example, for an architecture where the conversion between pointers to objects preserves the representation, you can use:

char a, b, …;
#define NULL1 (&a)
#define NULL2 (&b)

      

+7


source


Strictly speaking, NULL

it is not required to be numerically null at runtime. C takes 0

and NULL

in the context of an invalid pointer to address implementation-defined. This address is often numerically zero, but this is not guaranteed by the C standard, as far as I know, C itself does not provide any invalid addresses other than NULL

.



+3


source


You can also create your own "invalid" address pointer:

const void* const SOME_MARKER = (void*) &x;

If you make sure that x

(or its address) can never be used when you want to use SOME_MARKER

, you must be secure and 100% portable.

+3


source







All Articles