malloc() in Linux - “there is no guarantee that the memory really is available”?

前端 未结 2 1356
没有蜡笔的小新
没有蜡笔的小新 2020-12-21 01:57

I\'m making a game where the world is divided into chunks of data describing the world. I keep the chunks in a dynamically allocated array so I have to use malloc()

2条回答
  •  悲&欢浪女
    2020-12-21 02:47

    This is not something you need to deal with from an application perspective. Users who don't want random processes killed by the "OOM killer" will disable overcommit themselves via

    echo "2" > /proc/sys/vm/overcommit_memory
    

    This is their choice, not yours.

    But from another standpoint, it doesn't matter. Typical "recommended" amounts of swap are so ridiculous that no reasonable amount of malloc is going to fail to have physical storage to back it. However, you could easily allocate so much (even with forced MAP_POPULATE or manually touching it all) to keep the system thrashing swap for hours/days/weeks. There is no canonical way to ask the system to notify you and give an error if the amount of memory you want is going to bog down the system swapping.

    The whole situation is a mess, but as an application developer, your role in the fix is just to use malloc correctly and check for a null return value. The rest of the responsibility is on distributions and the kernel maintainers.

提交回复
热议问题