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 delete

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!



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