|
From: Carlos d. M. <cg...@wo...> - 2002-09-03 16:22:50
|
>
>
> 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
if(!r){
[...]
free(p);
}
>
>
> Ioannis
>
> * Ioannis Vranos
> * Programming pages: http://www.noicys.cjb.net
> * Alternative URL: http://run.to/noicys
>
> -------------------------------------------------------
> This sf.net email is sponsored by: OSDN - Tired of that same old
> cell phone? Get a new here for FREE!
> https://www.inphonic.com/r.asp?r=urceforge1&refcode1=vs3390
> _______________________________________________
> Dev-cpp-users mailing list
> Dev...@li...
> TO UNSUBSCRIBE: http://www.noicys.cjb.net/devcpp/ub.htm
> https://lists.sourceforge.net/lists/listinfo/dev-cpp-users
|