Why does calling sbrk(0) twice give a different value?

后端 未结 1 1921
独厮守ぢ
独厮守ぢ 2020-12-06 10:28

I\'m trying to understand the sbrk() function.

From what I know:
sbrk(0) returns the current address of the break and doesn\'t increm

相关标签:
1条回答
  • 2020-12-06 10:47

    Your program performs the following sequence of calls:

    sbrk()
    printf()
    sbrk()
    printf()
    ...
    

    The first call to printf calls malloc internally to allocate a buffer for stdout (stdout is line buffered by default, but the buffer is created on demand the first time you print to it).

    That's why the second call to sbrk returns a different value.

    (This answer is not directly related, but the error messages from valgrind expose the existence of the underlying malloc call hidden inside printf.)

    Your second example performs all sbrk calls up front, so there are no surprises from other functions calling malloc behind your back.

    0 讨论(0)
提交回复
热议问题