#define TRASHIT(x) do {(x) = (void *)-1;} while (0)
I meet this macro in the sys/queue.h, and google it but find nothing useful about this.
This macro set the pointer x to (void *)-1, but what does the (void *)-1 mean? What is the difference between this and NULL?
It's setting x to a pointer value for which dereferencing is probably undefined behaviour (as it's unlikely you own the memory, if any, at that address).
The do while(0) loop is a fairly standard idiom used when writing macros: it compels the user to append a semicolon when using it and can help control the scope of variables introduced in the macro's implementation. Of course, the statement within the loop is executed exactly once.
Most likely this is meant to be an invalid pointer different from NULL to be used as sort of flag or indication of error. We can find an example of this kind of us in the man page for shmat it says (emphasis mine):
On success shmat() returns the address of the attached shared memory segment; on error (void *) -1 is returned, and errno is set to indicate the cause of the error.
so in order to flag an error shmat returns (void *) -1 which is an invalid pointer with a distinct value.
The question Is ((void *) -1) a valid address? deals with the validity of such a pointer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With