1

I am wondering what does: (char*)-1 mean and what does it evaluate to?
It is a return value from sbrk() in case of an error.

ManmeetP
  • 801
  • 7
  • 17
Vikas Yadav
  • 322
  • 2
  • 9
  • 2
    Odd: my `man sbrk` gives `void *sbrk(int incr);` as its declaration. Could you show and quote where you got that information from? –  Nov 26 '17 at 09:00
  • See https://linux.die.net/man/2/sbrk for details – Ed Heal Nov 26 '17 at 09:01
  • @Evert Yeah, I've found a few platform-dependent definitions online already, the [freeBSD one](https://github.com/lattera/freebsd/blob/master/lib/libstand/sbrk.c) uses `char *` and is probably fairly reliable. – hnefatl Nov 26 '17 at 09:01
  • (char*)-1 is an invalid pointer value. "On error, (void *) -1 is returned, and errno is set to ENOMEM" from the man page. memory management functions return `void *` not `char *` – Jean-François Fabre Nov 26 '17 at 09:02
  • (funny as I could not put -1 at the start of my comment, the system thought I wanted to express my downvote :)) – Jean-François Fabre Nov 26 '17 at 09:02
  • 1
    I'm pretty sure this is just a way to return `-1` as a value from a function that normally returns a pointer - why they don't return `nullptr` instead is probably for legacy, but assigning it to a negative value is valid. It's not a dupe of the marked question, as that's specifically about assigning to a pointer address, whereas this is purely returning a value. – hnefatl Nov 26 '17 at 09:05
  • `brk` returns 0 when Ok, -1 when error. `sbrk` may mimic this error scheme. – Jean-François Fabre Nov 26 '17 at 09:06
  • 2
    This was closed with a **wrong** duplicate - now **this** is the correct one. – Antti Haapala -- Слава Україні Nov 26 '17 at 09:08
  • 1
    @VikasYadav: it is a pointer value that will not occur during normal operation. Given a 2's complement integer, signed -1 has the same bit-pattern as the maximum value for the unsigned version of the same integer type. So the implementers of this function knew that sbrk will not normally return the largest possible memory address. Apparently they thought it more plausible that the break might be set at 0. – lockcmpxchg8b Nov 26 '17 at 09:13
  • 1
    Code returning `(char*) -1` probably is pre-C89 code, stone-age old K&R C, from times where `void*` wasn't part of C yet. – alk Nov 26 '17 at 09:17

0 Answers0