How does sbrk() work? How does sbrk() work? unix unix

How does sbrk() work?


sbrk(n) increments the break by n and returns the old value of the break.

Thus:

    printf("end of the break : %p\n", sbrk(0));

Output: end of the break : 0xaa6000

Initially, the break is 0xaa6000 and the sbrk call doesn't change it.

    printf("end of the break : %p\n", sbrk(10));

Output: end of the break : 0xac7000

This is the value you're asking about. Above I said sbrk(0) wouldn't change the break, so why do we get a different value here?

The only thing that's happened in between the two sbrk call is the call to the first printf. Presumably the internals of your stdio implementation use malloc (e.g. to create buffers), which in turn calls sbrk itself. In other words, printf calls malloc internally, which reserves memory using sbrk.

    printf("new end of the break : %p\n\n", sbrk(0));

Output: new end of the break : 0xac700a

This time we see an increment of 0xa, which matches your previous sbrk(10) call exactly. Apparently this time printf didn't need to allocate dynamic memory (or if it did, malloc was able to do everything within the space it got from the first sbrk, so it didn't have to request more from the OS).