1. Computing & Technology

Discuss in my forum

C Tutorial - About Pointers

By , About.com Guide

8 of 10

Some Rules for Working with Pointers

Some Rules with Pointers

These are more common sense than hard and fast rules.
  • Always Initialize pointer variables.
  • With strings, never forget to include the terminating '\0' when calculating the storage size.
  • Check the return value of malloc() and make sure it's not NULL before using it then cast it to the desired type.
  • For every malloc() there is an equal and opposite free()!
  • Remember that &variable is a pointer.
  • After freeing a pointer always set it to NULL.
For example.
int * pint=(int *)malloc(sizeof(int)) ;
/*
Do something with pint
*/
free(pint) ;
pint = NULL;
Setting pint to NULL is a safety feature. Just because the memory has been released by the call to free() does not prevent it accidentally being reused. This could lead to a nasty bug. Forcing it to NULL will show any "freed pointer reuse" bugs much sooner.

Calloc and Realloc

There are two other less popular C functions relating to memory allocation: calloc() allocates multiple objects of a specified size- basically it is allocating an array and clears every element to 0. The realloc() function changes the size of an allocated block. I tend to avoid both as the number of times that you need realloc are few and it needs careful error checking. If you need to initialize an array then you can use calloc() or use the C function memset() found in <memory.h> or <string.h>. This sets a block of memory to a value.
fred = (int *) malloc(sizeof(int)) ;
memset(fred,0,sizeof(int)) ;
printf("Value of *fred = %i",*fred) ;
free(fred) ;
Although memset() uses an int for the value it's writing, if the value is non zero then you may get an interesting result as it writes the specified value into each of the bytes. Writing 0 gives 0 but 0xFF gives -1 which is the signed value 0xFFFFFFFF.

On the next page : More examples of using pointers

©2012 About.com. All rights reserved.

A part of The New York Times Company.