开发者

Is -1 a valid pointer address [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Can a pointer (address) ever be negative?

I'm considering initialising a structure to all -1s with memset(since it uses no signed numbers and zero is a valid value).

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

P.S. I'm trying to initialize a struct that is not all pointers and where zero is valid to all invalid like values so I can optionally do partial initialization in one function and initialise the non initialised fields to default values later on. If there is a pattern/stra开发者_运维问答tegy to do this in c?


In general, the only valid pointer values are NULL, and pointers to the beginning, inside, and right after, an existing object. Also note that NULL does not necessarily have to be represented as a bit-pattern with zero:s.

On some architectures, -1 is a legal pointer value. Some microcontrollers have RAM in the low part of memory, and read-only memory (like flash) in the upper parts.


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

In general, memset is intended to set bytes, not pointers. C does not make any guarantees as to how individual bytes combine to make a pointer. Even if your solution works, you'll have to document how and why it works.

A better idea, when NULL is a valid value, is to set all pointers to a sentinel of an 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 that value. This is self-documenting.


Negative numbers are usually stored in implementation defined manner. Some implementations use 1's complement to store negative numbers, others use 2's complement.

and are there any other problems with my idea?

The code might not be portable across implementations.


On any real world desktop or server system, -1 cast to a pointer is equivalent to the all-bits-one pointer representation, and it is not a valid pointer. Assuming pointer addition takes place as integer addition, if a pointer p has the all-bits-one representation, p+1 is going to be the all-bits-zero pointer, which in the real world is the null pointer.

Nonetheless, none of this is guaranteed by the standard.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜