Is malloc deterministic?

后端 未结 7 1518
一整个雨季
一整个雨季 2020-12-14 07:05

Is malloc deterministic? Say If I have a forked process, that is, a replica of another process, and at some point both of them call the malloc

相关标签:
7条回答
  • 2020-12-14 08:10

    That depends entirely on the malloc implementation. There's no inherent reason why a particular malloc implementation would introduce non-determinism (except possibly as an application fuzzing test, but even then it ought to be disabled by default). For example, Doug Lea's malloc does not use rand(3) or any similar methods in it.

    But, since malloc makes calls to the kernel such as sbrk(2) or mmap(2) on Linux or VirtualAlloc on Windows, those system calls may not always be deterministic, even in otherwise identical processes. The kernel may decide to intentionally provide different mmap'ed addresses in different processes for whatever reason.

    So for small allocations, which are usually serviced in user space without a system call, it will quite likely be the case that the resulting pointers will be the same after a fork(); large allocations that are serviced by a system a call can be the same.

    In general, though, do not depend on it. If you really need identical pointers in separate processes, either create them before forking, or use shared memory and share them appropriately.

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