Question

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

Was it helpful?

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)

OTHER TIPS

It could be that the sizes you use are too small, so that there is some form of rounding happening inside sbrk(). I would never expect byte-level precision for something like this, it's more likely to work in units of pages (which are 4 KB or thereabouts on typical Linux systems).

Also, note that the manual says:

Avoid using brk() and sbrk(): the malloc(3) memory allocation package is the portable and comfortable way of allocating memory.

It's likely that malloc() knows about any limitations sbrk() has and handles them, it's the preferred application-level interface.

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

  a = sbrk(2);
  printf("%p\n", a);

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

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

Output:

0x560267a31000
0x560267a52000
0x560267a52002
0x560267a52001

According to manual void *sbrk(intptr_t increment) return old value of brk when success. sbrk(0) return current brk.

printf uses malloc and thereby increases the data segment size

Try it out without using printf and print out your results by using a debugger. It will work fine and the result will be as expected. The heap will get incremented by 2 and decremented by -1, as intended.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top