Is “Out Of Memory” A Recoverable Error?

后端 未结 24 2099
闹比i
闹比i 2020-11-30 21:44

I\'ve been programming a long time, and the programs I see, when they run out of memory, attempt to clean up and exit, i.e. fail gracefully. I can\'t remember the last time

24条回答
  •  佛祖请我去吃肉
    2020-11-30 22:11

    I have this:

    void *smalloc(size_t size) {
      void *mem = null; 
      for(;;) {
       mem = malloc(size);
       if(mem == NULL) {
        sleep(1);
       } else 
         break;
      }
      return mem;
    }
    

    Which has saved a system a few times already. Just because you're out of memory now, doesn't mean some other part of the system or other processes running on the system have some memory they'll give back soon. You better be very very careful before attempting such tricks, and have all control over every memory you do allocate in your program though.

提交回复
热议问题