[C++] Dynamic Memory Allocation

A C++ program allocates and de-allocates dynamic block of memory from a global store of memory, sometimes called the heap. The “new” and “delete” operators manages the assignment of blocks from heap memory to the program and the restoration of those blocks to the heap. 

 

1. new and delete operators

The “new” operator which is used with a pointer allocates memory for the item from the heap and assigns the address to the pointer.

data_type *variable = new data_type;

The “delete” operator returns the heap memory to the system.

delete variable;

You can initialize the dynamically allocated memory by specifying the initial value inside parentheses.

int *i = new int(1);
*i = 10;
cout << *i << endl; // 10
delete i;

 

2. Arrays

You can use new and delete to acquire and dispose of memory for arrays. Be careful with the syntax of deleting an array. The square brackets tell the array is being deleted.

int* iArr = new int[10];
int total = 0;
for (int i=0; i<10; i++)
  iArr[i] = i+1;
for (int i=0; i<10; i++)
  total += iArr[i];
cout << total << endl; // 55
delete [] iArr;

 

3. Structures and Classes

Using new and delete operators for only a single instance of an intrinsic type(such as int, float..) is not the best use of the heap. A more typical use is to allocate memory for an instance of a structure or a class.

class Point
{
public:
  int X; int Y;
  Point(int a=0, int b=0): X(a), Y(b){};
};

int main()
{
  Point *p = new Point(10, 20);
  cout << p->X << ", " << p->Y << endl; // 10, 20
  delete p;
  return (EXIT_SUCCESS);
}

 

4. Heap Exhaustion

The heap is not infinite in size. A program must be prepared to deal with conditions wherein the heap is exhausted. The C++ run-time system includes an internal function pointer that is called when an allocation error occurs.

If the error occurs, the system throws a ” std::bad_alloc ” exception.

The <new.h> declares a function named ” std::set_new_handler ” that enables you to assign the address of a new handler function.

void my_new_handler(..);
std::set_new_handler(my_new_handler);

Simply you can check the pointer is null after calling the “new” operator.

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s