Re: malloc/free question
- From: Keith Thompson <kst-u@xxxxxxx>
- Date: Thu, 13 Jul 2006 21:57:35 GMT
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.
--
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.
.
- Follow-Ups:
- Re: malloc/free question
- From: Stephen Sprunk
- Re: malloc/free question
- From: Al Balmer
- Re: malloc/free question
- References:
- malloc/free question
- From: Snis Pilbor
- Re: malloc/free question
- From: Al Balmer
- malloc/free question
- Prev by Date: Re: Writing a incrementing/decrementing function with roll-over
- Next by Date: Re: C is too old? opinions?
- Previous by thread: Re: malloc/free question
- Next by thread: Re: malloc/free question
- Index(es):
Relevant Pages
|