|
From: Carlos d. M. <cg...@wo...> - 2002-09-03 12:03:49
|
Hi: I got a C library reference from cplusplus.com, and in realloc there is something I'm not sure about. There it is said that after the call to realloc, this 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 = (int*)realloc(numbers, newsize); That made me think, if the pointer provided is left untouched, and in case of error it returns NULL; it wouldn't be a bad programming practice use the same pointer as the parameter and the returning value? Could it generate a memory leak? Perhaps that means that after the call you have two allocated memory blocks, one of the previous size and another with the new size, if you use the same pointer as parameter and return value then either if it succeds or not you'll get a memory block which won't be freed and will behave badly, so you'll need to free it manually 8which seems a little bad feature, at least when the call succeeds), and if it fails you either lose a chance to recover with the original pointer (would be nice only if it fails). But then I made a little experiment for see this. I made more or less this code: int* bufferone, *buffertwo; bufferone = (int*)malloc(2 * sizeof(int)); for(int i = 0; i < 2; i++) bufferone[i] = i + 1; for[] cout bufferone[i]; buffertwo = (int*)realloc(bufferone, 4 * sizeof(int)); cout << bufferone << " " << buffertwo << endl; for[] buffertwo[i] = i + 1; for[] cout << bufferone[i]; for[] cout << buffertwo[i]; free(bufferone); fors for cout; free(buffertwo) again the for couts. After realloc, bufferone : 1 2; buffertwo: 1, 2, 3, 4. The same address for both. After free(bufferone) bufferone: 0, 2; buffertwo: 0, 2, 3, 4. After free(buffertwo) bufferone: 49855478, 2; buffertwo: 49855478, 2, 3, 4. Or different addresses: before frees and after realloc bufferone has been freed, and bufferone[0] is 48716817 (any number), then after free(bufferone) bufferone[0] has 4816871687, and buffertwo[0] has 1; and after free(buffertwo) bufferone[0] has 4816871687 and buffertwo[0] has 0. If I use realloc(buffertwo, 0); then the value stored in the direction where the pointer pointed to as the first member of the array is left untouched, buffertwo[0] gives 1. If I use buffertwo = (int*)realloc(buffertwo, 0); then the program is closed by windows with its classic dialog, this program has to been closed. So I deduce, you can do numbers = (int*)realloc(numbers, newsize); because what pointer as parameter being untouched means seems to be: the value of it, the direction to which it points to is the same, but the memory it points to is either increased, or moved and freed in that point, so after the call you won't can use it, at least if it succeeds, and I'd bet that neither it is useful if it fails, which I think makes more sense. |