I was looking at the documentation of sbrk
system call and found this:
On success,
sbrk()
returns the previous program break. (If the break was increased, then this value is a pointer to the start of the newly allocated memory). On error,(void *) -1
is returned, anderrno
is set toENOMEM
.
Now,
What's the significance of (void *) -1
?
What is the exact memory address it points to? (if it does at all)
How is it guaranteed that (void *) -1
is not a valid address
that can be returned by sbrk()
on success?
(void *) -1 == (size_t) -1
It's 0xFFFFFFFF
on 32 bit machine and 0xFFFFFFFFFFFFFFFF
on 64 bit machine, an invalid address that is supposed to be bigger than any other address.
- What's the significance of
(void *) -1
?
It's simply a sentinel value that sbrk()
would be incapable of returning in a successful case.
- What is the exact memory address it points to? (if it does at all)
It's not expected to be a valid address, and the specific value is not relevant.
- How is it guaranteed that
(void *) -1
is not a valid address that can be returned bysbrk()
on success?
It perhaps seems like circular reasoning, but it's guaranteed because sbrk()
guarantees it as part of its contract. (For example, sbrk()
could check whether it would return that value if successful; if so, it instead could do nothing and report failure.)
In practice, (void*) -1
on most modern machines is going to be 0xFF...FF
, which would be the highest possible address, and that's simply something that's unlikely to be valid.
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