Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is -1 a valid pointer address [duplicate]

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?

like image 713
Roman A. Taycher Avatar asked Oct 21 '25 13:10

Roman A. Taycher


2 Answers

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.

like image 79
Fred Foo Avatar answered Oct 24 '25 01:10

Fred Foo


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.

like image 29
Lindydancer Avatar answered Oct 24 '25 02:10

Lindydancer