Should we check if memory allocations fail?

后端 未结 7 1906
温柔的废话
温柔的废话 2020-12-31 08:41

I\'ve seen a lot of code that checks for NULL pointers whenever an allocation is made. This makes the code verbose, and if it\'s not done consistently, only when the program

7条回答
  •  半阙折子戏
    2020-12-31 08:48

    In a hosted environment error checking the return of malloc makes not much sense nowadays. Most machines have a virtual address space of 64 bit. You'd need a lot of time to exhaust that. Your program will most likely fail at a completely different place, namely when your physical+swap memory is exhausted. It will have shown completely ridiculous performance before that, because it only was swapping and the user will have triggered Cntrl-C long before you ever come there.

    Segfaulting "nicely" on a null pointer reference would be a clear point to see where things fail in a debugger. But in my practice I have never seen a failed malloc as a cause.

    When programming for embedded systems the picture changes completely. There you definitively should check for failed malloc.

    Edit: To clarify that after the edit of the question. The kind of programs/systems described there are clearly not "embedded". I have never seen malloc fail under the circumstances described there.

提交回复
热议问题