Why are malloc() and printf() said as non-reentrant?

后端 未结 6 1507
深忆病人
深忆病人 2020-11-29 19:25

In UNIX systems we know malloc() is a non-reentrant function (system call). Why is that?

Similarly, printf() also is said to be non-reent

6条回答
  •  -上瘾入骨i
    2020-11-29 20:04

    It's because both works with global resources: heap memory structures and console.

    EDIT: the heap is nothing else than a kind linked list structure. Each malloc or free modifies it, so having several threads in the same time with writing access to it will damage its consistency.

    EDIT2: another detail: they could be made reentrant by default by using mutexes. But this approach is costly, and there is no garanty that they will be always used in MT environment.

    So there are two solutions: to make 2 library functions, one reentrant and one not or leave the mutex part to the user. They've choosed the second.

    Also, it can be because the original versions of these functions were non-reentrant, so the've been declared so for compatibility.

提交回复
热议问题