Search code examples
cglibcsbrk

can sbrk(0) fail?


I'd like to know if someone already seen sbrk(0) fail ?

I mean, if you can reach this function you obviously had the rights to access the memory before, so to check the current break location should be ok, right ?

EDIT : Should I consider an error exception for example ?


Solution

  • The documents states that:

       sbrk() increments the program's data space by increment bytes.
       Calling sbrk() with an increment of 0 can be used to find the current
       location of the program break.
    
      ...
    
       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.
    

    If you look at glibc implementation you will see:

    extern void *__curbrk;
      ...
    void *
    __sbrk (intptr_t increment)
    {
      ...
      if (increment == 0)
        return __curbrk; 
      ...
    

    there is no way it will fail since it just returns the current value of __curbrk if increment is zero.