I am just starting to learn C and (of course) struggling with pointers :)
Given this snippet:
int *storage, *storage_p;
storage = malloc(sizeof(int[GROW_BY]));
storage_p = storage;
// do something with storage, using storage_p
free(storage);
storage = NULL;
Is it really necessary to have two variables declared to work with the malloc()
'ed data? Is it good practice to create a storage
and storage_p
the way I did? If not, what would would be 'the way'?
You will need a pointer that will hold the value returned by malloc(), so that you can free it later.
If what you plan on using storage_p for is going to change it value, then you are going to need two pointers.
However, I generally keep the pure initial pointer, and create new ones, ad hoc, as I need one.
int *storage = (int*) malloc(sizeof(int[GROW_BY]));
// :
int* ptr = storage;
while (*ptr)
{
// :
++ptr;
}
I would only duplicate a pointer that was created by malloc for one reason: I want to modify it.
For example, If you were iterating through a character array you allocated with malloc, I would copy the pointer to a new variable to iterate through and leave the first one untouched.
Also when it comes to dynamic allocation, take a look at free lists, they simplify a lot:
http://en.wikipedia.org/wiki/Free_list
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With