Search code examples
cmallocsbrk

Sbrk and negative parameter


I am running into a problem when i am freeing memory using sbrk. I pass sbrk a negative value but it doesnt decrement the start of the heap. Here is the code

int main(int argc, char** argv) {
    void * a = sbrk(0);
    printf("%p\n",a);

    sbrk(2);
    sbrk(-1);
    a = sbrk(0);
    printf("%p\n",a);
}

And here is sample output:

0x10734f000

0x10734f002

I don't understand why the printed value isn't coming back as 0x10734f001 after sbrk is decremented by one.

I am not allowed to use malloc in this program. This is for a custom implementation of malloc and free using sbrk


Solution

  • Just tested it with MacOSX Mavericks and sbrk() behaves (nearly) the same than on Linux with two exceptions:

    • I get a compiler warning: tst21.c:12:6: warning: 'sbrk' is deprecated [-Wdeprecated-declarations]
    • it doesn't seem to be possible to give back memory to the OS using a negative value (this is - as far as I remember - the same behaviour observed on SYSV4 decades ago: releasing memory allocated by sbrk() wasn't possible)