What does this macro mean?

#define TRASHIT(x)  do {(x) = (void *)-1;} while (0)

      

I come across this macro on sys/queue.h

and google it doesn't find anything useful about it. This macro sets the pointer x

to (void *)-1

, but what does it mean (void *)-1

? What is the difference between this and NULL

?

+3


source to share


4 answers


Most likely it means an invalid pointer other than NULL

to be used as some kind of flag or error indication. We can find an example of this type in the man page for shmat which says (emphasis mine):

On success, shmat () returns the address of the attached shared memory segment; on error (void *) -1 is returned , and errno is the reason for the error.



so to flag an error, it shmat

returns (void *) -1

which is an invalid single-valued pointer.

Question Is ((void *) -1) valid address? deals with the validity of such a pointer.

+1


source


It sets the x

value of the pointer, for which dereferencing is probably undefined behavior (since it is unlikely that you own memory, if any, at that address).



A loop do

while(0)

is a fairly standard idiom used when writing macros: it forces the user to add a semicolon when using it, and can help control the scope of variables introduced into the macro implementation. Of course, the statement in the loop is executed exactly once.

+1


source


The standard does not specify behavior for

(void*)-1;

      

except to suggest making the mapping between integers and pointers natural to underlying frameworks accessing the model.

Thus, if your implementation allows you to create invalid pointers, it will most likely be the value of a void pointer with all bits set.

A null pointer is represented in the source by a constant integral expression (possibly different from void*

) or by a specific implementation method.
On most modern systems, this is a null pointer with all digits.

So, while the two may be the same , this is unlikely , especially on modern systems.
Also, this second is highly unlikely to be a valid pointer .

+1


source


It's just to return the type of error, I think, just like below:

#define TRASHIT(x)  do {(x) = (void *)-1;} while (0)

void* foo (void) {

    void* ret;

    if(fail) {
        TRASHIT(x);
    }
    else {
        sometingelse(x);
    }

    return ret;
}

      

0


source







All Articles