Is -1 a valid pointer address [duplicate]

瘦欲@ 提交于 2019-12-12 13:54:34

问题


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/strategy to do this in c?


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/5377077/is-1-a-valid-pointer-address

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!