Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

significance of (void*) -1 [duplicate]

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, and errno is set to ENOMEM.

Now,

  1. What's the significance of (void *) -1?

  2. What is the exact memory address it points to? (if it does at all)

  3. How is it guaranteed that (void *) -1 is not a valid address that can be returned by sbrk() on success?

like image 764
tomol Avatar asked Jul 24 '16 09:07

tomol


2 Answers

(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.

like image 185
MichaelMoser Avatar answered Nov 11 '22 09:11

MichaelMoser


  1. What's the significance of (void *) -1?

It's simply a sentinel value that sbrk() would be incapable of returning in a successful case.

  1. 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.

  1. How is it guaranteed that (void *) -1 is not a valid address that can be returned by sbrk() 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.

like image 2
jamesdlin Avatar answered Nov 11 '22 11:11

jamesdlin