On Jan 10, 2:27*pm, sandysimon...@gmail.com wrote:
> Hi,
>
> I think this is a pretty silly reply - just think of "local variables"
> vs. "malloced memory" if you have hang-ups with the stack and the
> heap...
>
> I guess to rephrase what I'm asking... we tend to think of the stack
> being for small allocations and the heap for big ones. But it isn't
> always so.
>
> For example, I've seen some really paranoid code, where *every*
> malloc() is checked to see if it returned NULL, even if it's only for
> like 10 bytes to copy a string.
>
> This is pretty pointless, if the function checking malloc so carefully
> can't pick up the fact that it failed to allocate three local int
> variables say, taking up a whopping 12 bytes...
It's not pointless. Failing to check every malloc, or equivalent, is
simply an indication of a grievously flawed program. Now in some
sample or test code it's perhaps not unreasonable to omit, but
certainly nothing like that should ever make it into any kind of
production system. OTOH, the failure of most mallocs is simply a
fatal error, and it's quite reasonable to have a small wrapper around
malloc along the lines of:
void * mustmalloc(size_t s)
{
void *p;
p = malloc(s);
if (!p)
KaBoom(); /* issue diagnostic and abend */
return p;
}
> And just like you can malloc small amounts, you can also use up lots
> of stack memory by declaring huge arrays as local variables. There
> surely ought to be some way to recover if this fails.
If I fatally run out of stack space, I hope the implementation will
abend the program at that point. And most do.
It's relatively rare that a program can successfully recover from a
failing memory allocation. Even when a program does it, it's usually
only for a very limited portion of the allocations (for example,
storage allocated for buffering a large data file). In most cases
avoidance is a much better idea.
The thing you *don't* want to do is wander back into your program with
bad pointers, buffer overflows, and whatnot, which might cause all
sorts of havoc long after the failing memory allocation.