Some Rules with Pointers
These are more common sense than hard and fast rules.- Always initialize pointer variables.
- If you use C strings, never forget to include the terminating '\0' when calculating the storage size.
- Check that new doesn't generate an exception or return 0.
- For every new there is an equal and opposite delete()!
- For arrays you must use the [] for both new and delete. Don't free with delete() something allocated with new()[] and vice versa.
- After you've deleted a pointer, set it to 0.
int * pint=new int ;Setting pint to 0 is a safety feature. Just because the memory has been released by the call to delete() does not prevent it accidentally being reused. This could lead to a nasty bug but delete() does nothing with a 0 value pointer.
/*
Do something with pint
*/
delete pint ;
pint = 0;
New is more than just malloc()
You might be wondering why not just malloc(), especially if you know C. Two reasons- new is typesafe. Whereas malloc() returns a void *, new returns an object of the specified type.
- malloc() does not initialise memory whereas new calls a constructor on an object.
// ex3.cppThe output from this is:
#include <iostream>
using namespace std;
struct s{
int a;
double d;
s() {a =9;d=9.999;}
};
int main(int argc, char* argv[])
{
s * value = new s;
cout << "Value of value.a = " <<
value->a << " value.d = " << value->d << endl;
return 0;
}
Value of value.a = 9 value.d = 9.999Download Example 3.
This shows that the constructor s() was called.
On the next page : More examples of using pointers

