Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is ((void *) -1) a valid address?

Verbatim from Linux' man shmat:

RETURN VALUE

[...] on error (void *) -1 is returned, and errno is set to indicate the cause of the error.

(POSIX tells the same using a slightly different wording.)

Is there any mandatory rule or definition (standard?) that (void *) -1 may not be a valid address?

like image 990
alk Avatar asked Nov 09 '12 11:11

alk


People also ask

Does NULL pointer have address?

Memory address 0 is called the null pointer. Your program is never allowed to look at or store anything into memory address 0, so the null pointer is a way of saying "a pointer to nothing". Note that a null pointer is not the same as a null character; do not confuse the two.

What is a dangling pointer in C++?

Dangling pointer is a pointer pointing to a memory location that has been freed (or deleted).

How do you declare a function pointer in C++?

We declare the function pointer, i.e., void (*ptr)(char*). The statement ptr=printname means that we are assigning the address of printname() function to ptr. Now, we can call the printname() function by using the statement ptr(s).


2 Answers

0xffffffff is technically a valid address in a 32 bit environment but on most operating systems (Certainly Linux/Windows) will be in the reserved kernel part of the address space. That means that in user mode processes it's safe to use it as a error code since no user mode allocation function would return this as a usable address.

like image 110
Benj Avatar answered Sep 25 '22 21:09

Benj


For simplicity, consider a machine with 16 bits of address space. This machine can address memory from 0 to 65535. In this case (void*) -1 would be the same as 0xffff which is 65535. While technically this address is valid, there are few system that would have anything there that they would allow to be accessed.

The other thing to consider is that almost all POSIX system calls returns -1 on error.


As noted by Benj, it's actually possible to map the address NULL. This can be used for example when you want to see if there is a mapping with a specified shmid, in which case the shmaddr argument is set to NULL and the function return NULL to signify that the shared memory exists.

like image 24
Some programmer dude Avatar answered Sep 25 '22 21:09

Some programmer dude