Re: an interesting problem in c
- From: sam_cit@xxxxxxxxxxx
- Date: 19 Dec 2006 06:25:16 -0800
#include <stdlib.h>
int main(void)
{
int *tmp = NULL;
size_t n = 1024;
int *p = malloc(n * sizeof *p);
if(p != NULL)
{
int i;
for(i = 0; i < n; i++)
{
p[i] = i;
}
/* now let's try to get some more memory */
n *= 2;
tmp = realloc(p, n * sizeof *p);
if(tmp == NULL)
{
/* the allocation FAILED, but because we used tmp to detect
this, we can still get to the old block, using p, which
still points to the old block.
*/
}
else
{
/* the allocation SUCCEEDED. p is now invalid, but we can
safely fix that now:
*/
p = tmp;
while(i < n)
{
p[i] = i;
etc etc etc
--
I see what you are trying to say, to consider the return value of
re-alloc() when it is successful and when it fails, stick to the old
pointer. And i' m trying to understand as to how re-alloc() works, does
it try to allocate memory at the end of the current chunk and if it
can't do because memory next to current chunk is not free, it would
allocate a whole new block to hold old value and copies old value to
new block making sure new memory is good enough to satisfy the memory
request and free the old block...
Is my understanding correct?
.
- Follow-Ups:
- Re: an interesting problem in c
- From: Richard Heathfield
- Re: an interesting problem in c
- References:
- an interesting problem in c
- From: sam_cit
- Re: an interesting problem in c
- From: mark_bluemel
- Re: an interesting problem in c
- From: sam_cit
- Re: an interesting problem in c
- From: Richard Heathfield
- Re: an interesting problem in c
- From: sam_cit
- Re: an interesting problem in c
- From: Richard Heathfield
- an interesting problem in c
- Prev by Date: Re: size of pointers
- Next by Date: Re: regarding pointer operation in a printf function call
- Previous by thread: Re: an interesting problem in c
- Next by thread: Re: an interesting problem in c
- Index(es):
Relevant Pages
|
|