Dynamic Memory Management
Shehzad Ashraf Ch.
• Arrays are fixed size
e.g. int arr;//creates an array having 20 elements of type int
//(reserves 40 bytes of memory for arr)
Array is assigned the memory at compile time, so we can’t wait until
run time to specify the size of array
int arr[size]; // error array size must be a constant
• In many cases It can’t be known in advance how
much memory is needed at compile time.
– e.g. We want to store the string typed by user
• in the above case we can define an array sized to hold the
largest string we expect. what if we created an array of size
1000 and string length entered by user is just 5. its simply the
wastage of memory.
Dynamic Memory Allocation
• C++ provides an operator new for obtaining a variable-
length block of memory
– new takes memory from Operating system and returns the
starting address (pointer) of obtained memory. The pointer
returned by new is of the appropriate type.( i.e. the type of
contents of reserved memory )
e.g. cin>>size;//takes value of size from user
int* p=new int[size];//Reserves memory for an array of size entered by user and
// stores starting address of reserved memory to p .
– In above case the pointer returned by new is of type int.
char* pstr=new char;//reserves 100 bytes of memory and returns the pointer of
//reserved memory to pstr. Here pointer returned by new is
//of type char.
float* pf=new float;//reserves 4 bytes of memory and returns pointer of reserved
//memory to pf, pointer returned by new is of type float
Dynamic Memory De-allocation
• The memory allocated by new can be de-allocated by delete
• To ensure efficient use of memory, C++ provides new operator with
a matched corresponding delete operator, which returns memory to
e.g. int* pI=new int;