티스토리 뷰

C++

Dynamic Allocation in C++

seoca 2018. 11. 3. 10:22



Why do we use Dynamic Allocation? 

In C++, the address placed in the stack memory is removed when the program ends. However, the heap memory maintains the memory until it's deallocated manually by a programmer. The stack memory can be used to store them for a small amount of memory. It causes overflow when the stack is exceeded to limit. On the other hand, the heap has no limit for the size of memory. So, it is essential for a programmer to know how to allocate heap memory properly.
 

 
You may allocate the heap memorin the following cases

  • When you want to keep the variable (e.g global variable) for a long term. 
  • When a large size of an array or struct allows changing the size dynamically.  


You may allocate the stack memory in the following cases

  • When you deal with only the small amount of memory which doesn't need to shrink or grow dynamically. 
  • When your memory has size limits
  • When the memory doesn't need to be managed 

 



Example code 



 



1. Initialize Dynamic Allocation

int *studentScore = new int[studentNum];
new int assign the 4-byte memory to pointer as an integer data type from OS(operating system).




2. delete Dynamic Allocation

delete[]studentScore;
You must do deallocate the memory manually that you don't use anymore to prevent a memory leak




3. delete the address of the pointer 

studentScore = NULL;

Even though the memory deleted, the address of the pointer has still existed which has garbage value.  0 or NULL or nullptr has to be assigned to the pointer to delete the address.






Result



'C++' 카테고리의 다른 글

Reference in C++  (0) 2018.11.06
Class and Object in C++  (0) 2018.11.06
Function Overloading in C++ with example code  (0) 2018.11.03
Call by reference & Call by value with example code  (0) 2018.11.03
Array and Pointer example  (0) 2018.10.31