Static Memory Allocation | Dynamic Memory Allocation |
---|---|
In static memory allocation, memory is allocated before the execution of the program begins. | In Dynamic memory allocation, memory is allocated during the execution of the program. |
Memory allocation and deallocation actions are not performed during the execution. | Memory allocation and deallocation actions are performed during the execution. |
Static memory allocation, pointer is required to access the variables. | It does not require pointers to allocate the variables dynamically. |
It performs execution of program faster than dynamic memory. | It performs execution of program slower than static. |
It requires more memory space. | It requires less memory space. |
The data in static memory is allocated permanently. | The data in dynamic memory is allocated only when program unit is active. |
#include <iostream>
using namespace std;
int main ()
{
int *ptr = NULL; // Pointer initialized with null
ptr = new int; // Request memory for the variable
*ptr = 12345; // Store value at allocated address
cout << "Value of Pointer Variable *ptr : " << *ptr << endl;
delete ptr; // free up the memory.
return 0;
}
#include <iostream>
using namespace std;
class Test
{
public:
Test()
{
cout << "Constructor called..." <<endl;
}
~Test()
{
cout << "Destructor called!!" <<endl;
}
};
int main( )
{
Test* t = new Test[2];
delete [] t; // Delete array
return 0;
}