I often catch myself doing the following (in non-critical components):
some_small_struct *ptr=(some_small_struct *) malloc(sizeof(some_small_struct));
ptr->some_member= ...;
In words, I allocate dynamically memory for a small structure and I use it directly without checking the malloc'ed pointer. I understand there is always a chance that the program won't get the memory it asks for (duh!) but consider the following:
If the program can't even get some memory for a small structure off the
heap, maybe there are much bigger problems looming and it doesn't matter after all.
Furthermore, what if handling the null pointer exacerbates the precarious situation even more?? (e.g. trying to log the condition calls even more non-existing resources etc.)
Is my reasoning sane (enough) ?
Updated:
- A "safe_malloc" function can be useful when debugging and might be useful otherwise
+X
access can hide the root cause of a NULL pointer
- On Linux, "optimistic memory allocation" can shadow loomin OOM (Out-Of-Memory) conditions
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…