C++ Review: Memory Management
Statically allocated objects
Object’s size is fixed at compile time, and for the entire lifetime of the program.
int x;
float y;
Point p;
Dynamically allocated objects
Use a pointer – a variable that holds the address of another variable.
Only the pointer is fixed at compile time. The memory address it points to can change.
In C++, managing dynamic memory is done using the operators new and delete.
new
- creates an object of the specified type
- calls the appropriate constructor
- returns a pointer of the specified type
delete
- calls the destructor
- deallocates the memory associated with the object
Examples: Using new and delete
First:
#include
Simple data type:
int *x = NULL; // x is a pointer to an int
x = new int;
*x = 5;
Or, use the constructor to create and initialize the object:
x = new int(3);
User defined class:
Point *p = NULL;
p = new Point;
delete p;
p = new Point(1, -3);
Arrays:
double *numbers = NULL;
numbers = new double[10];
for (int i = 0; i < 10; i++)
numbers[i] = i;
delete[] numbers;
Common pitfalls
int *n = new int[50]; // alloate an array of 50 integers
int *n = new int(50); // allocate an integer with value 50
float *array;
array = new float[100];
delete array; // will only delete the first element in the array
delete [] array; // delete the entire array
Important!
- Initialize your pointers.
int *n = NULL;
- Check the return value of new.
int *n = new int;
if (n == NULL)
cout << “Error!” << endl;
- Don’t use a pointer before using new
double *d;
*d = 18;
delete d;
- Or after using delete
int *n = NULL;
n = new int;
*n = 5;
delete n;
*n = 3;
- Use delete when you’re done!
Created by Gali Diamant gali@cs.bu.edu, spring 2003.
Material partially taken from the textbook "How to Program C++", by Deitel and Deitel.
Last Modified Jan 22, 2003