significance of (void*) -1 [duplicate]

可紊 提交于 2020-01-11 05:33:08

问题


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?


回答1:


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




回答2:


  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.



来源:https://stackoverflow.com/questions/38550401/significance-of-void-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!