C++ Memory Management Notes

Memory Management

C++ has good support for dynamic memory management, which is, memory that you allocate and reclaim manually as opposed to memory automatically allocated by the compiler on the stack.

In both C and C++ you could call malloc and free from stdlib.h to manage memory but C++ introduces the new and delete keyword operators to do this.

Examples for dynamically allocating storage for a single instance of a type:

int *i = new int;
double *x = new double(10.0);
Circle *c = new Circle;
Pt *p = new Pt(1.0, 2.0);

The object initialization takes place after the allocation, so specify the appropriate comma delimited list of arguments in parenthesis as demonstrated above.

You can also use new to allocate an array of an object:

int *i = new int[24];
char *str = new char[256];

The class for the objects being allocated must have a default constructor; which means, the constructor for that class must have either no parameters or all the parameters have default values.

To deallocate memory that was previously allocated with new, use the keyword operator delete:

File *f = new File;
...
delete f;

Before memory reclamation from delete, the appropriate destructors are automatically called. Then to delete an array of objects allocated with new[], use delete[]:

File *f = new File[4];
...
delete[] f;

As a warning, it is recommended that you use the delete operators on the same objects that have been allocated with new or new[]; If you used new to allcoate an object, use delete to deallocated it, if you used new[], then use delete[] later if you need to.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: