I'm trying to understand how sbrk works.
Here is my little code:
int main()
{
printf("end of the break : %p\n", sbrk(0));
printf("end of the break : %p\n", sbrk(10));
printf("new end of the break : %p\n\n", sbrk(0));
}
This outputs:
end of break : 0xaa6000 end of break : 0xac7000 new end of the break : 0xac700a
Why is the difference between the first 2 addresses 0xac7000 - 0xaa6000 = 21000 and not 10?
sbrk(n)increments the break bynand returns the old value of the break.Thus:
Output:
end of the break : 0xaa6000Initially, the break is 0xaa6000 and the
sbrkcall doesn't change it.Output:
end of the break : 0xac7000This 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
sbrkcall is the call to the firstprintf. Presumably the internals of your stdio implementation usemalloc(e.g. to create buffers), which in turn callssbrkitself. In other words,printfcallsmallocinternally, which reserves memory usingsbrk.Output:
new end of the break : 0xac700aThis time we see an increment of 0xa, which matches your previous
sbrk(10)call exactly. Apparently this timeprintfdidn't need to allocate dynamic memory (or if it did,mallocwas able to do everything within the space it got from the firstsbrk, so it didn't have to request more from the OS).