본문 바로가기

22년 2학기 학교공부

OOP with C++ (2) - Dynamic memory allocation and deallocation

목차

    728x90
    반응형
    SMALL

    Stack data structure

    A stack is a data structure in which last-in data is firstly popped out ○ We call it Last In First Out (LIFO)

     

    Function call stack

    Lots of programming language runtimes utilizes a call stack to manage function calls ○ A call stack is a stack that stores functions’ local data ○ When calling a function, the callee function data is pushed onto the call stack ○ When returning a function, the function data is popped out from the call stack

     

    Stack memeory allocation

    Local data is allocated on the call stack ○ Parameters, local variables, local objects and arrays, … ○ The size of memory to be allocated is known to compiler ○ Whenever a function is called, its variables get memory allocated on the stack ○ Whenever the function call is over, the memory for the variables is deallocated ■ Don’t need to consider memory alloc/dealloc of stack variables

     

    Heap memory allocation

    Memory is allocated on a heap ○ Call it dynamic memory allocation ○ The size of memory to be allocated is calculated at runtime ○ The allocated memory is valid for long-time before deallocating it ■ Need to explicitly alloc/dealloc memory ■ Be careful to avoid memory leak or dangling pointer errors

    => Node* n = new Node(3) : 3이라는 값을 넣은 Node가 heap에 생기고 그 주소가 foo로 옴

    * new Node는 클래스니까 생성자를 부르는거임 heap 안에 오브젝트를 만들어서 그 공간을 주는건데

    malloc은 그냥 heap 안에 특정 크기만큼만 두는거임

    뭔소리야

    deallocation : free(), delete ..

     

    Dynamic allocation with new keyword

    A keyword new is used to allocate memory in C++ ○ Basically, it works as the same as malloc ○ But, it creates an object and invokes its constructor as well ○ It is paired with delete keyword ■ it works as the same as free ■ But, it deletes an object and invokes its destructor as well

     

    728x90
    반응형
    LIST