|
From: Abhijit S. <mu...@gm...> - 2002-09-03 17:03:09
|
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 fail
use the returned pointer and forget the old one. Example:
/* C code */
int *p=malloc(100*sizeof(*p));
int *r=realloc(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 second
part with the experiment:
numbers = (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 = BUF_SIZE;
*ptr = (char *)malloc(BUF_SIZE); // Assuming success
*tmp_ptr = realloc(ptr, NEW_BUF_SIZE);
if(tmp_ptr)
{
free(ptr);
ptr = tmp_ptr;
tmp_ptr = NULL;
buf_size = NEW_BUF_SIZE;
}
___________________________________________________________
Abhijit Shylanath
E-mail: mu...@gm... || ibr...@bi...
Web-site: http://mudeth.tripod.com/
|