Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer best practice

Tags:

c

pointers

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'?

like image 254
Dennis Haarbrink Avatar asked Feb 27 '23 14:02

Dennis Haarbrink


2 Answers

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;
}
like image 53
James Curran Avatar answered Mar 07 '23 00:03

James Curran


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

like image 43
Bob Fincheimer Avatar answered Mar 07 '23 02:03

Bob Fincheimer