2

I'm trying to learn more about memory management (mmap, brk, sbrk) genuinely confused as to how:

    char *ptr = sbrk(0);
    char *ptr2 = ptr + 100000;
    *ptr2 = 8;
    printf("%d\n", *ptr2);

Doesn't trigger a segmentation fault? I'm compiling this with clang on OS X Mojave.

The man page for sbrk() says that says that it's deprecated, but it also says that sbrk() should reliably return the program break. If that's true, and the pagesize is 4096 bytes, then shouldn't setting a value for an address 100000 spaces beyond the program break trigger a segfault? If it doesn't reliably return the program break (which it can't, if you can set values for addresses beyond it right?) then how do you reliably find the program break on Mac OS?

The exact same code produced a segfault on Ubuntu 18.10.

Thanks!

tmte
  • 21
  • 2
  • *undefined behavior* means you cannot guarantee anything – UnholySheep Feb 21 '19 at 23:12
  • `Doesn't trigger a segmentation fault?` - having code that seg faults is one thing. Expecting the code to seg fault is another. You can't expect it to seg fault. It may. – KamilCuk Feb 21 '19 at 23:16
  • 1
    That makes perfect sense. My apologies for the ignorance, thanks guys! – tmte Feb 21 '19 at 23:20
  • Hello, welcome to Stack Overflow. I recommend reading [Eric Lippert's answer about undefined behaviour](https://stackoverflow.com/a/6445794/3982001), it contains a great example that is very easy to understand and remember. – Fabio says Reinstate Monica Feb 21 '19 at 23:48

0 Answers0