When you declare a variable in C such as int i;, space in memory is allocated to store that variable. This is called static memory allocation. Some data items are large and you do not wish to allocate space for them unless you need it. Other times, you do not know if you need a data item until the program is being run. For these reasons, C allows programs to request memory for a particular data item when they need it. This is called dynamic memory allocation.
Dynamic memory allocation in C is done using the library functions malloc and free. Here we will demonstrate the memory commands new and free. These are actually part of C++, but they are simpler to understand.
The new command is used to allocate memory for a new data item. It returns a pointer to the item it has just allocated memory for. If memory could not be allocated, it returns null. The format is simply:
new <data type to allocate>;For example,
float *budget; //pointer to type float budget = new float; //allocate storage space for it //check to make sure the allocation succeded if(budget == NULL) { printf("Memory allocation failed for variable budget\n"); }
The delete command is used to free memory that has been allocated with new. For instance,
delete budget; //free the space allocated for budgetIf an array is being deleted, the syntax is as follows:
delete [] array;
Most often, new and delete are used with complex data types like structures or arrays. The principles are the same as with the float in the above example.