Can I rely on malloc returning NULL?

后端 未结 4 913
独厮守ぢ
独厮守ぢ 2020-11-27 22:19

I read that on Unix systems, malloc can return a non-NULL pointer even if the memory is not actually available, and trying to use the memory later on will trigg

4条回答
  •  没有蜡笔的小新
    2020-11-27 22:43

    On Linux, you can indeed not rely on malloc returning NULL if sufficient memory is not available due to the kernel's overallocation strategy, but you should still check for it because in some circumstances malloc will return NULL, e.g. when you ask for more memory than is available in the machine in total. The Linux malloc(3) manpage calls the overallocation "a really bad bug" and contains advice on how to turn it off.

    I've never heard about this behavior also occurring in other Unix variants.

    As for the "spasms of paging", that depends on the machine setup. E.g., I tend not to setup a swap partition on laptop Linux installations, since the exact behavior you fear might kill the hard disk. I would still like the C/C++ programs that I run to check malloc return values, give appropriate error messages and when possible clean up after themselves.

提交回复
热议问题