|
From: Carlos d. M. <cg...@wo...> - 2002-09-03 19:09:00
|
The point is that with realloc, if it succeeds the original memory pointe=
d by
the argument pointer is freed and so you can forget it and work with the =
new,
but if it fails, then the memory pointed to by the argument pointer remai=
ns
valid, and if you use that same pointer as return value, then you get tha=
t the
pointer is no more pointing to that piece of still valid memory, and, how=
you
free it? it will be annoying your program.
The moral of the story is, don't use the same pointer as argument and ret=
urn
value of realloc.
If it fails, if(!returnpointer) work with the original and free(original)
if it succeeds else work with the new and forget the old.
Abhijit Shylanath escribi=F3:
> Greets, Carlos.
>
> ----- Original Message -----
>
> DON'T USE MALLOC()/CALLOC()/REALLOC() IN C++ PROGRAMS! ONLY IN C.
> WITH ALL THE HIGHLIGHTED WORDS MALLOC FOR C, NEW FOR C++ (WITH THE
> CORRESPONDENT "LIBERATORS")
> Now regarding realloc():
> If it manages to change the size at the current location it returns the
> same pointer you passed to it. If it allocates space somewhere else, it
> moves the contents there and frees the current space. In case it fails,
> it returns NULL and the current memory address remains unchanged.
> In summary, if it fails you have the old memory area. If it doesn't fai=
l
> use the returned pointer and forget the old one. Example:
> /* C code */
> int *p=3Dmalloc(100*sizeof(*p));
> int *r=3Drealloc(p, 120*sizeof(*r));
> if(!r)
> /* use the old p */
> /* use the new r and forget p address */
> I tried to make an example reasigning to a so big block that it couldn'=
t be
> succeeding (I did something like realloc(pointer,
> 15545454554545455454545454554545); but then windows closed the console,=
and
> I couldn't see the result.
> So, in the end, just what I feared at first, but couldn't prove the sec=
ond
> part with the experiment:
> numbers =3D (int*)realloc(numbers, newsize);
> is a practice better to avoid. Because if it fails then you get a block=
of
> memory which had been allocated , but not freed. so
>
> ------------------------------
>
> Then maybe this?
>
> char *ptr, *tmp_ptr;
> int buf_size =3D BUF_SIZE;
>
> *ptr =3D (char *)malloc(BUF_SIZE); // Assuming success
> *tmp_ptr =3D realloc(ptr, NEW_BUF_SIZE);
> if(tmp_ptr)
> {
> free(ptr);
> ptr =3D tmp_ptr;
> tmp_ptr =3D NULL;
> buf_size =3D NEW_BUF_SIZE;
> }
> ___________________________________________________________
>
> Abhijit Shylanath
>
> E-mail: mu...@gm... || ibr...@bi...
> Web-site: http://mudeth.tripod.com/
|