Re: malloc/free question
- From: "Stephen Sprunk" <stephen@xxxxxxxxxx>
- Date: Thu, 13 Jul 2006 18:45:08 -0500
"Keith Thompson" <kst-u@xxxxxxx> wrote in message news:ln4pxl6ucx.fsf@xxxxxxxxxxxxxxxxxx
Al Balmer <albalmer@xxxxxxx> writes:On 13 Jul 2006 10:53:41 -0700, "Snis Pilbor" <snispilbor@xxxxxxxxx>
wrote:
Howdy C warriors =)3, but tending toward 2.
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?
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.
Cite? I thought realloc() is not allowed to fail or move the block if the requested size is the same or smaller than the existing block. Realistically, is there any implementation out there (other than the DS9k) where that assumption doesn't hold? Even if the block moves, that's a standard problem with using realloc() which needs to be dealt with in most cases, so it's good to get in the habit.
With only 20 bytes being returned and the size of the bookkeeping overhead for malloc() et al to track those 20 bytes and try to reuse them (if possible), it's almost not worth the effort to bother shrinking the block. Keeping a second list with those extra 20 bytes may be worth the easier disposal of the blocks, plus it may reduce heap fragmentation as a bonus.
S
--
Stephen Sprunk "Stupid people surround themselves with smart
CCIE #3723 people. Smart people surround themselves with
K5SSS smart people who disagree with them." --Aaron Sorkin
--
Posted via a free Usenet account from http://www.teranews.com
.
- Follow-Ups:
- Re: malloc/free question
- From: Snis Pilbor
- Re: malloc/free question
- From: Keith Thompson
- Re: malloc/free question
- From: Richard Heathfield
- Re: malloc/free question
- References:
- malloc/free question
- From: Snis Pilbor
- Re: malloc/free question
- From: Al Balmer
- Re: malloc/free question
- From: Keith Thompson
- malloc/free question
- Prev by Date: Re: Cool Ebooks Site
- Next by Date: Re: malloc/free question
- Previous by thread: Re: malloc/free question
- Next by thread: Re: malloc/free question
- Index(es):
Relevant Pages
|