In general, a modern malloc()
implementation will return NULL
only as an absolute last resort, and trying again will definitely not help. The only thing that will help is freeing some memory and then trying again. If your application holds any expendable resources, this would be the time to free them, and then give it another shot.
In some environments, a useful practice is to allocate a small amount of memory as a rainy-day fund. If malloc()
ever does return NULL
, you can free that rainy-day fund, and then allocate whatever resources you need to be able to handle the error and exit gracefully. This was a common practice when programming with the old Macintosh Toolbox; if malloc()
returned NULL
, you could use that space to create a dialog to report the problem before exiting.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…