Re: malloc/free question



Al Balmer <albalmer@xxxxxxx> writes:
On 13 Jul 2006 10:53:41 -0700, "Snis Pilbor" <snispilbor@xxxxxxxxx>
wrote:
Howdy C warriors =)

I'd like to be able to malloc a block of memory, then later free just a
certain (trailing or leading) portion of it. For example, malloc 100
bytes, then later free the last 20 of them. If I just blindly do
something like free(myptr + 80), will this:

1. be guaranteed to do what I want and safely free the last 20 bytes,
2. be guaranteed to corrupt memory, or
3. have behavior dependent on implementation and not nailed down by C
specifications?

3, but tending toward 2.

Use realloc.

I recommended this myself, but be careful. As somebody pointed out,
realloc() may relocate the object, even if the requested size is
smaller than the original size. For that matter, it's not even
guaranteed that a realloc() requesting a smaller size will succeed;
there's probably no good reason for it to fail, but you should always
check the result anyway, and be prepared to deal with a failure.

--
Keith Thompson (The_Other_Keith) kst-u@xxxxxxx <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
.



Relevant Pages

  • Re: malloc/free question
    ... I'd like to be able to malloc a block of memory, ... For example, malloc 100 ... Use realloc. ... seriously consider using two lists. ...
    (comp.lang.c)
  • Re: [OT]Re: malloc
    ... so all malloc calls *always* return a pointer to memory. ... realloc() or reallocfwill be ... initialization only happens once for each byte, ...
    (comp.lang.c)
  • Re: malloc/free question
    ... I'd like to be able to malloc a block of memory, ... For example, malloc 100 ... Use realloc. ... guaranteed that a reallocrequesting a smaller size will succeed; ...
    (comp.lang.c)
  • Re: realloc() implicit free() ?
    ... >>> If realloc() finds it necessary to move the memory block, ... > malloc implementations already out there. ... malloc allocates continious memeory i.e one Block while ...
    (comp.lang.c)
  • Re: Querry (Newbe)
    ... > If we do the realloc then it means that we have allocated the ... > extended memory for the current memory, ... > which I extendend to realloc if compiler allocates memory ... > what is the diffrence between the callocand malloc() ...
    (comp.lang.c)