Always check malloc'ed memory?

后端 未结 10 901
滥情空心
滥情空心 2020-12-09 03:05

I often catch myself doing the following (in non-critical components):

some_small_struct *ptr=(some_small_struct *) malloc(sizeof(some_small_struct));
ptr-&g         


        
10条回答
  •  温柔的废话
    2020-12-09 03:37

    In the case of C, it depends on the platform. If you are on an embedded platform with very little memory, you should alweays check, thouggh what you do if it does fail is more difficult to say. On a modern 32-bit OS with virtual memory, the system will probably become unresponsive and crash before it admits to running out of memory. In this case, the call to malloc never returns, so the utility of checking its value becomes moot.

    In the case of C++, you should be using new instead of malloc, in which case an exception will be raised on exhaustion, so there is no point in checking the return value.

提交回复
热议问题