Dynamic Memory Allocation (I)
Dynamic Memory Allocation (I)
●
In addition to these, the operating system provides and extra
amount of memory called Heap.
What is a dynamic memory
allocation?
●
double * dp;
●
Tells the compiler to have a pointer dp that will hold the
starting address of a variable of type double in heap memory
Syntax for Dynamic Variable
z
(contd...)
To create the dynamic variable new is used.
Will create a dynamic variable of type double and makes dp pointer point to
its starting address
●
delete operator is used to delete the memory
●
allocated for the dynamic variable in heap
●
(Syntax):- delete dp;
●
- Will delete 8 bytes of the memory allocated for the double variable
●
NOTE: the dp pointer will not be erased as it is created in code/data
segment and can be point some other dynamically allocated memory
location
Allocating dynamic arrays
●
C++ also provides the possibility to allocate an entire array in the heap
●
- int *table;
●
- table = new int[100];
Assigns 100 * sizeof(int) = 100 * 4 = 400 bytes of memory and assign the starting address to
table pointer
●
Arrays defined in heap are similar to the ones defined in data and code
segments and can be accessed using [ ]
●
For (int i = 0; i < 100; i++)
- table[i] = 0; will initialize all the array items to zero
Deleting dynamic array
●
Again delete operator is used
- [ ] is used will delete operator to tell the compiler that you are deleting arrays not
variables
●
(Syntax):- delete [ ] table;
●
will delete not only the memory location pointed by table but all
the items in the array
Common mistakes made in dynamic allocation
●
Freeing an already freed variable
char *str = new char [100];
delete [] str;
delete [] str; // error
●
Freeing a dynamic variable not assigned yet
char *str;
delete str; // error
●
Accessing or assigning value to the freed variable
int *str = new int[100];
delete [] str;
str[10] = 90; // error
Dynamic Memory Allocation for Objects
Output
Code
Example:
Code
Output
z
Thank You!
By Aryan Choudhary
Roll No.-28
BCA-3A