Always check malloc'ed memory?

后端 未结 10 877
滥情空心
滥情空心 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:50

    I always feel it is important and best to handle the return of malloc or any other system call for that matter. Though in modern systems (apart from embedded ones) it's a rare scenario unless and until your code uses too much memory, it's always safer.

    Continuing the code after a system call failure can lead to corruption, crash and what not apart from making your program look bad.

    Also, in linux, memory allocated to a process is limited. Try creating 1000 threads in a process and allocate some memory in each one of them, then you can easily simulate the low memory condition. : )

    Always better to check for sys call return values!

    0 讨论(0)
  • 2020-12-09 03:55

    Depends on the platform. For instance, on Linux (by default) it does not make much sense to check for NULL:

    http://linux.die.net/man/3/malloc

    By default, Linux follows an optimistic memory allocation strategy. This means that when malloc() returns non-NULL there is no guarantee that the memory really is available. This is a really bad bug. In case it turns out that the system is out of memory, one or more processes will be killed by the infamous OOM killer.

    0 讨论(0)
  • 2020-12-09 03:58

    Yes, having insufficient memeory will almost certatinly presage other failures coming soon. But how sure are you that no corrupt output will occur between the failure to allocate and the final crash?

    How sure are you for every program, every time you make an edit.

    Catch your errors so you can know you crashed on time.

    0 讨论(0)
  • 2020-12-09 03:59

    It is possible to allocate a largish chunk of memory at startup that you can free when you hit an out of memory condition and use that to shut down gracefully.

    0 讨论(0)
提交回复
热议问题