Let's suppose I have a char* initialized to NULL and I use the realloc function to allocate fifty bytes for it. Now let's say I use only twenty-five bytes and I want to keep those allocated but free the rest. Is that possible?
Let's suppose I have a char* initialized to NULL and I use the realloc function to allocate fifty bytes for it. Now let's say I use only twenty-five bytes and I want to keep those allocated but free the rest. Is that possible?
I'm not totaly sure on this, but I think you could use realloc again. Something like
Code:char *buffer = NULL; buffer = realloc(buffer, 50); if(buffer == NULL) { // Error } // Do something char *smaller = realloc(buffer, 25); if(smaller == NULL) { // Error } else { buffer = smaller; }
Do you really need to realloc?
cant you just determine how much you are going ot use then use malloc? There is no need to use realloc the first time because there is no space allocated to it to begin with.
>There is no need to use realloc the first time because there is no space allocated to it to begin with.
realloc can be used as if it were malloc if the first argument is a null pointer, and it can be used as if it were free if the second argument is 0. This can make it simpler to write algorithms for dynamic growth without special cases, but it can also be confusing.
My best code is written with the delete key.
It is not confusing, it's just a matter of reading the function's definition and understanding it.
I'm talking like that because I think I finally get it lol.
>It is not confusing, it's just a matter of reading the function's definition and understanding it.
No, it is confusing because the function does more than one thing and all of those things are conceptually different. A function is easier to understand if it doesn't try to be three functions.
My best code is written with the delete key.
Prelude, will the use of realloc as "free" make the above example look like this:
And this leaves the data stored in *buffer intact, right?Code:char *buffer = NULL; buffer = realloc(buffer, 50); if(buffer == NULL) { // Error } // Do something buffer = realloc(buffer, 0); if(buffer == NULL) { // Error }
mw
Last edited by Lionmane; 08-28-2005 at 10:27 AM.
Blucast Corporation
> And this leaves the data stored in *buffer intact, right?
There is no data - the size you passed is 0.
In the same way that malloc(0) may or may not return a NULL pointer, and free(ptr) doesn't affect the value stored in the pointer, you can't legally dereference any of those pointers.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.