Re: When to check the return value of malloc



Kelsey Bjarnason wrote:

<snip>

And that's exactly what xmalloc does: it allows me to request the 64MB
I'd like, but prevents me from detecting the failure and adjusting the
request.

You complain that malloc causes problems. Even assuming you had a
point, your solution is worse than the problem. At least with malloc,
*I* can adjust to conditions. *I* can choose to use a smaller buffer.
*I* can detect the error and decide that perhaps I should try another
task, then check back later to see if memory is available. With your
code, no such options are available.

Granted, with your "user function" or whatever you call it, I can, in
principle, say "try again, with a smaller amount of memory", but that
doesn't help, as I cannot tell the calling code that the change has
occurred; it asked for 64MB, what was *actually* allocated was 16MB,
how the hell does it know that? It doesn't - there's no way to
respond back that the request was not honoured.

You can set a global variable from the call-back to tell the higher
level code the amount of memory that was actually allocated. Ugly, but
doable.

<snip>

.



Relevant Pages

  • Re: Weird. malloc() fails in spite of having enough virtual memory...
    ... request, it forks itself and lets its child process handles the ... And then, I free those containers. ... there should be no memory explosion issue. ... I always see malloc() failure as it reads ...
    (comp.lang.c)
  • Re: How to choose buffer size?
    ... Some malloc() implementations use fundamental "block sizes" ... request is very nearly the worst thing you can ask for. ... needs to find twice as much memory as you requested ... ... a size slightly below a power of two, ...
    (comp.lang.c)
  • Re: Weird. malloc() fails in spite of having enough virtual memory...
    ... request, it forks itself and lets its child process handles the ... there should be no memory explosion issue. ... I always see malloc() failure as it reads ...
    (comp.lang.c)
  • Re: Freeing memory - will it be available immediately
    ... - should a memory block borrowed from the OS should ... It does not specifiy the behavior of malloc ... - should malloc only request memory from the OS ... available for further allocation. ...
    (comp.lang.c)
  • Re: Doubts on C
    ... Is their limit for alloctaing the memory for calloc and malloc, ... > i,e total memory of the Heap I can allocate in one slot. ... largest value you can REQUEST is the largest value you can pass to the ...
    (comp.lang.c)