What if malloc fails?

前端 未结 10 583
轮回少年
轮回少年 2020-12-09 08:57

If a malloc allocation fails, should we try it again?

In something like this:

char* mystrdup(const char *s)  
{
    char *ab = NULL;

           


        
10条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-09 09:18

    In a single-threaded program "trying again" without freeing any memory between tries make no practical sense. It will just loop forever.

    In a multi-threaded program this might "work", if another thread running in parallel suddenly decides to free some of its own memory. The loop in such case would constitute a classic "busy waiting" loop. But even in this case such code has very little practical value for more reasons than one.

提交回复
热议问题