Skip to content
Advertisement

What is “(void*)-1” in the context of sbrk’s return value?

The Linux Man Page for sbrk() states that upon failure, it returns (void*) -1. What is (void*) -1 and does it have any significance or is it simply a number that could never actually be a void* which is cast to a void* just to meet the function signature of returning a void*? I ask this because I’ve never seen a pointer to a negative address before. I did not know this was possible to dereference on any platform.

Advertisement

Answer

In most operating systems, memory is allocated in a set of pages (these can be in physical RAM or they can be virtual pages that are stored on a permanent storage disk/device and are usually 4KB each). Since -1 (unsigned 0xFFFFFFFFFFFFFFFF or 0xFFFFFFFF for 32 bit) is the largest possible value for a QWORD (or DWORD for 32 bit) a page usually cannot start at this address because it is the very last address in the address space. Therefore -1 is a good value to use to indicate an error in memory allocation because it is usually considered a non-existent page. As for a pointer to a negative address, your compiler is responsible for enforcing sign in its code generation if you ever have had experience with assembly you will recall that a variable doesn’t implicitly have sign (only the instructions give it this property). When you access a region of memory in assembly the address is considered to be an unsigned number.

Advertisement