티스토리 뷰
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 memory in 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 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- algorithm
- hackerrank javascript solution
- math.max
- 프로그래머스 알고리즘문제
- 프로그래머스
- C++
- 프로그래머스 알고리즘
- string class in java
- Collection Framework
- Javascript Algorithm
- easy javascript algorithm
- Object type casting
- repeat()
- easy algorithm
- HackerRank Algorithm
- substring()
- 알고리즘
- spring boot application
- compareTo()
- rest parameter
- HashMap
- code refactoring
- javascript
- ... in Javascript
- java
- hackerrank javascript
- hackerrank
- hackerrank solution
- math.abs
- equals()
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
글 보관함