There is -1 valid pointer address

Possible duplicate:
Can the pointer (address) be negative?

I am considering the possibility of initializing the structure for all -1 with memset (since it uses no signed numbers and zero is not a valid value).

Is there -1 a valid pointer address? and are there any other problems with my idea? note: platform - linux / gcc / x86

PS I'm trying to initialize a structure that is not all pointers, and where zero is valid for all invalid identical values, so I can optionally perform partial initialization in one function and later initialize non-initialized fields with default values. If in c?

there is a template / strategy,
+3
source share
4 answers

The interpretation -1as a pointer is architecture dependent and therefore unreliable.

In general, it is memsetintended to set bytes, not pointers. C makes no guarantees as to how individual bytes are combined to make a pointer. Even if your solution works, you will have to document how and why it works.

The best idea when it NULLis a valid value is to set all the pointers to the patrol of the appropriate type. So, if your structure has a field int *ip:

static const int sentineli;

// in the initialization:
foo->ip = (int *)&sentineli;

then compare with this value. This is self-documenting.

+3
source

NULL , , . , NULL - : s.

-1 - . (, ) .

+3

. 1 , 2 .

- ?

.

+1

In any real desktop or server system, -1 casting to a pointer is equivalent to representing a pointer to all bits, and it is not a valid pointer. Assuming that adding a pointer takes place as an integer adding, if the pointer phas an all-bit-1 representation, it p+1will be a pointer to all bits-zero, which in the real world is a null pointer.

However, none of this is guaranteed by the standard.

0
source

All Articles