user136298
0
Q:

dynamic memory allocation in c++

int length = 69;
int * numbers = new int[length];
delete[] numbers;
3
Example:
        int *p = new int[10]
4
// Release block of memory 
// pointed by pointer-variable
delete[] pointer-variable;  

Example:
   // It will free the entire array
   // pointed by p.
   delete[] p;
1
In the dynamic memory allocation the memory is allocated during run time.
The space which is allocated dynamically usually placed in a program segment which is known as heap.
In this, the compiler does not need to know the size in advance.
In C++, dynamic memory allocation means performing memory allocation manually by programmer.
It is allocated on the heap and the heap is the region of a computer memory which is managed by the programmer using pointers to access the memory.
The programmers can dynamically allocate storage space while the program is running but they cannot create a new variable name.
  
Example:
0
char* pvalue  = NULL;         // Pointer initialized with null
pvalue  = new char[20];       // Request memory for the variable
0
#include <iostream>
using namespace std;

int main () {
   double* pvalue  = NULL; // Pointer initialized with null
   pvalue  = new double;   // Request memory for the variable
 
   *pvalue = 29494.99;     // Store value at allocated address
   cout << "Value of pvalue : " << *pvalue << endl;

   delete pvalue;         // free up the memory.

   return 0;
}
0
#include <iostream>
#include <string>

using String = std::string;
class Entity
{
private:
	String m_Name;
public:
	Entity() : m_Name("Unknown") {}
	Entity(const String& name) : m_Name(name) {}
	const String& GetName() const {
		return m_Name;
	};
};
int main() {
  // new keyword is used to allocate memory on heap
	int* b = new int; // new keyword will call the c function malloc which will allocate on heap  memory = data and return a ptr to that plaock of memory
	int* c = new int[50];
	Entity* e1 = new Entity;//new keyword Not allocating only memory but also calling the constructor
	Entity* e = new Entity[50];
	//usually calling new will  call underlined c function malloc
	//malloc(50); 
	Entity* alloc = (Entity*)malloc(sizeof(Entity));//will not call constructor only  allocate memory = memory of entity
	delete e;//calls a c function free
	Entity* e3 = new(c) Entity();//Placement New
0

New to Communities?

Join the community