|
From: Ioannis V. <no...@ho...> - 2002-09-03 13:42:26
|
> -----Original Message----- > From: dev...@li...=20 > [mailto:dev...@li...] On Behalf=20 > Of Carlos Garc=EDa del Monte > Sent: Tuesday, September 03, 2002 3:03 PM > To: dev-cpp-users-list > Subject: [Dev-C++] realloc >=20 >=20 > Hi: > I got a C library reference from cplusplus.com, and in=20 > realloc there is > something I'm not sure about. > There it is said that after the call to realloc, this=20 > function returns a > pointer to the new allocated memory or NULL if failed, and that the > original pointer provided to it as the first parameter is left > untouched. In their example they write: > numbers =3D (int*)realloc(numbers, newsize); > [...] DON'T USE MALLOC()/CALLOC()/REALLOC() IN C++ PROGRAMS! ONLY IN C. In C++ use new/new[]/delete/delete[] and standard containers. "[diff.malloc] C.2.4.2 Memory allocation functions 1 The functions calloc, malloc, and realloc are restricted in this International Standard. 20.4.6 describes the changes." 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=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 */ Ioannis * Ioannis Vranos * Programming pages: http://www.noicys.cjb.net * Alternative URL: http://run.to/noicys |