J
James Harris
I understand that a C pointer can have some basic arithmetic operations
applied to it such as having an integer added or subtracted to step a whole
number of the referred-to data type, or two pointers to the same data type
being subtracted. However....
To write a couple of memory management routines to implement malloc and free
it would be handy to take one bit from a pointer to use as an indicator of
whether a piece of memory is in use or is unused. Because each piece of
memory will be aligned any valid pointer will have its lower bit(s) clear so
it makes sense to take the lowest bit of a pointer and use it to indicate
whether a region is used or unused. That would lead to expressions like
these:
ptr |= 1;
ptr &= ~1;
if (ptr & 1) ...
My question is whether C's behaviour is defined or undefined for such
pointer manipulations. Would the pointers need to be cast to char pointers
for this to work? Any other issues I should be aware of?
I'm pretty sure that any implementation of C that I am likely to use will
allow the kinds of pointer masking that I have in mind but are there better,
more C-like ways to go about this? Are there implementations on which it
might not work? And would it be acceptable to manipulate the pointers as
pointers to char even though malloc and free are defined to work with
pointers to void?
James
applied to it such as having an integer added or subtracted to step a whole
number of the referred-to data type, or two pointers to the same data type
being subtracted. However....
To write a couple of memory management routines to implement malloc and free
it would be handy to take one bit from a pointer to use as an indicator of
whether a piece of memory is in use or is unused. Because each piece of
memory will be aligned any valid pointer will have its lower bit(s) clear so
it makes sense to take the lowest bit of a pointer and use it to indicate
whether a region is used or unused. That would lead to expressions like
these:
ptr |= 1;
ptr &= ~1;
if (ptr & 1) ...
My question is whether C's behaviour is defined or undefined for such
pointer manipulations. Would the pointers need to be cast to char pointers
for this to work? Any other issues I should be aware of?
I'm pretty sure that any implementation of C that I am likely to use will
allow the kinds of pointer masking that I have in mind but are there better,
more C-like ways to go about this? Are there implementations on which it
might not work? And would it be acceptable to manipulate the pointers as
pointers to char even though malloc and free are defined to work with
pointers to void?
James