Re: More questions on realloc
- From: Eric Sosman <eric.sosman@xxxxxxx>
- Date: Tue, 29 Nov 2005 12:22:31 -0500
James S. Singleton wrote On 11/29/05 12:01,:
> Thanks to everybody who provided an answer to my previous question on
> this. I am trying to grasp the nitty-gritty details of this, and I am
> having difficulties understanding some of the issues involved.
>
> According to the man page (and I quote)
>
> realloc(void *ptr, size_t size) changes the size of the memory block
> pointed to by ptr to size bytes. The contents will be unchanged to the
> minimum of the old and new sizes; newly allocated memory will be
> uninitialized.
>
> Let's assume the following sequence (my apologies for the sloppiness of
> my language in what follows; I am taking for granted that experienced C
> insiders will have no difficulty cutting through it):
>
> p = malloc(size1) ;
>
> /* Code to copy some stuff to the memory area pointed to by p */
>
> q = realloc(p, size2) ;
>
> For simplicity, I will assume that q != p. With this, my understanding is
> that realloc will copy the contents of p to q, to the appropriate length,
> and will then free p.
>
> My question is, how does realloc know that p points to a memory region
> size1 bytes in length? Or, to put it differently, can realloc be
> implemented with malloc, and no other memory management call?
The memory-management functions keep track of the
sizes of allocated and available blocks of memory. The
details of how this is done differ from one implementation
to another. One frequently-used method is to allocate a
little bit more memory than is requested, plant some
housekeeping data at the beginnning, and return a pointer
to the tail end. Later, free() or realloc() can look "just
before" the pointer they're given to find the housekeeping
data again.
... but that's just one way; others exist. From the
programmer's perspective, it's all "implementation magic,"
just like the machinery behind, say, fopen(). You don't
(usually) care how the spell is cast, just that the magic
happens.
--
Eric.Sosman@xxxxxxx
.
- References:
- More questions on realloc
- From: James S. Singleton
- More questions on realloc
- Prev by Date: Re: More questions on realloc
- Next by Date: Re: More questions on realloc
- Previous by thread: Re: More questions on realloc
- Next by thread: More questions on realloc - Thanks
- Index(es):
Relevant Pages
|