Machineboy空

Object-Oriented Data Structures # WEEK02 : Heap Memory 본문

Computer/자료구조

Object-Oriented Data Structures # WEEK02 : Heap Memory

안녕도라 2024. 2. 2. 10:47

2.2 Heap Memory

 

Unlike stack memory,

Heap memory allows us to create memory independent of the lifecycle of a function.

 

Heap Memory

If memory needs to exist for longer than the lifecycle of the function, we must use heap memory.

  • The only way to create heap memory in C++ is with the new operator

The new operator returns a pointer to memory storing the data - not an instance of the data itself.

  • memory address of starting of data

 

C++'s New Operator

The new operator in C++ will always do three things:

  1. Allocate memory on the heap for the data structure
  2. Initialize the data structure
  3. Return a pointer to the start of the data structure

The memory is only ever reclaimed(회수) by the system when the pointer is passed to the delete operator.

doesn't matter for function ends;

긴 수명 주기를 가질 것.

 

Heap Memory

 

The code below allocates two chunks of memory:

  • Memory to store an integer pointer on the stack
  • Memory to store an integer on the heap
int * numPtr = new int;

 

create enough heap memory to store integer

integer is pointed by pointer in stack memory.

 

stack memory points to heap memory.하는 상황

 

 

growes up

 

Memory Diagram


if main return , stack memory deleted but,

also have pointer that points memory doesn't contain data for anymore

 

solution for the null pointer

 

Nullptr

The C++ keyword nullptr is a pointer that points to the memory address 0X0.

  • nullptr represents a pointer to "nowhere"
  • Address 0X0 is reserved and never used by the system.
  • Address 0X0 will always generate an "segmentation fault" when accessed.
  • Calls to delete 0X0 are ignored.

way to provide safety.

 

We'd like to clarify some common misunderstandings. Remember that after the line "delete c;" the pointer c still stores the address of the deleted variable, which is no longer valid to dereference and is therefore dangerous. The pointer won't be automatically set to nullptr. Then, you should manually set c to nullptr if you want to better protect against coding mistakes:

delete c;

c = nullptr;

Also, this is a good practice in general whenever you use "delete" on a pointer, but in this particular example, the function that is about to return is "main". When main returns, the program exits and the operating system will usually release all the allocated memory back to the system. This isn't an excuse to be sloppy, though; as you will soon see, many class objects have their "destructor" functions called silently when the program exits, and mistakes can trigger crashes even during that process.


위 코드에서 (*c).setLength(4)인 부분은 절대쓰지 않고

->를 이용할것

 

Arrow Operator(->)

When an object is stored via a pointer, access can be made to memver functions using the -> operator:

c->getVolume();
...identical to...
(*c).getVolume();