C++ Pointers and Dynamic Memory

With pointers all memory needs were determined before program execution by defining the variables needed. But there may be cases where the memory needs of a program can only be determined during runtime. For example, when the memory needed depends on user input.

new – new[]

Dynamic memory is allocated using operator new.


// In this case, the system dynamically allocates space for five elements of type int and returns a pointer to the first element of the sequence
int * foo; 
foo = new int [5];

delete – delete pointer

In most cases, memory allocated dynamically is only needed during specific periods of time within a program; once it is no longer needed, it can be freed so that the memory becomes available again for other requests of dynamic memory.


// clear the memory
delete pointer;
delete[] pointer;

nothrow

When a memory allocation fails, instead of throwing a ‘bad_alloc exception’ or terminating the program, the pointer returned by new is a null pointer, and the program continues its execution normally.


// rememb-o-matic
#include <iostream>
#include <new>
using namespace std;

int main ()
{
  int i,n;
  int * p;
  cout << "How many numbers would you like to type? ";
  cin >> i;
  // no bad_alloc exception ##################
  p= new (nothrow) int[i];
  {
    for (n=0; n<i; n++)
    {
      cout << "Enter number: ";
      cin >> p[n];
    }
    cout << "You have entered: ";
    for (n=0; n<i; n++)
      cout << p[n] << ", ";
    // clear the momory #######################
    delete[] p;
  }
  return 0;
}

The result is:
How many numbers would you like to type? 3
Enter number : 12
Enter number : 23
Enter number : 34
You have entered: 12, 23, 34,

For italian people: come funziona?
1. p= new (nothrow) int[i]; -> evita che termini l’ersecuzione del software per un ‘bad_alloc exception’

2. alloca i valori di input utente cin <<... e li visualizza cout >>…

3. delete[] p; -> ripulisce la memoria