3
#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?

karllo
  • 341
  • 3
  • 10

4 Answers4

2

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.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
1

The standard does not prescribe any behavior for

(void*)-1;

except to suggest making the mapping between integral numbers and pointers natural for the underlying platforms addressing model.

Thus, if your implementation allows creation of invalid pointers, that will likely be a void-pointer value with all bits set.

A null pointer is represented in source by a constant integral expression (possibly cast to void*), or in some implementation-defined manner.
On most modern systems, it's a void-pointer with all bits clear.

So, while the two can be identical, that's unlikely, especially on modern systems.
Also, that second one is very unlikely to be a valid pointer.

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
1

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.

Community
  • 1
  • 1
Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
0

It's just for returning an error type, I think, just as below:

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

void* foo (void) {

    void* ret;

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

    return ret;
}
Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
David Lin
  • 1
  • 1