Under what circumstances can malloc return NULL?

前端 未结 9 1742
陌清茗
陌清茗 2020-12-23 14:17

It has never happened to me, and I\'ve programming for years now.

Can someone give me an example of a non-trivial program in which malloc will actually

9条回答
  •  误落风尘
    2020-12-23 15:11

    Pick any platform, though embedded is probably easier. malloc (or new) a ton of RAM (or leak RAM over time or even fragment it by using naive algorithms). Boom. malloc does return NULL for me on occasion when "bad" things are happening.

    In response to your edit. Yes again. Memory fragmentation over time can make it so that even a single allocation of an int can fail. Also keep in mind that malloc doesn't just allocate 4 bytes for an int, but can grab as much space as it wants. It has its own book-keeping stuff and quite often will grab 32-64 bytes minimum.

提交回复
热议问题