본문 바로가기

Language/C++

[C++] 동적할당(Dynamic memory allocation) - 컴도리돌이

728x90

C 언어 동적 할당

-> malloc(), free() functions

-> #include <stdlib.h>

 

#include<stdlib.h>

int* pnum = (int*)malloc(sizeof(int)); //pnum 포인터를 정수형 크기로 메모리 할당
free(pnum); // 사용한 pnum를 삭제

 

C++ 언어 동적 할당

->new, delete operators

 

new : 타입 또는 클래스에 대한 변수 또는 instance를 생성한다.

delete : new에 생성된 변수 또는 instance를 삭제한다.

new [] : 타입 또는 클래스에 대한 변수 또는 instance의 배열을 생성한다.

delete [] : new []로 생성된 배열을 삭제한다.

 

//One instance Allocate and Deallocate

int* pnum = new int;
delete pnum;


//Array Allocate and Deallocate

int* pnum = new int[];
delete[] pnum;

 

<example>

#include<iostream>
//#include<stdlib.h> -> c언어 version


using namesapce std;

int main() 
{
	int n;
    cin >> n;
    
    int* num = new int;
    // int* num = (int*)malloc(sizeof(int));-> c언어 version
    int* numArr = new int[n];
    // int* numArr = (int*)malloc(sizeof(int)*n);-> c언어 version
    
    *num = n;
    
    for(int i= 0; i< n ;i ++)
    {
    	cout<< numArr[i] << " ";
    }
    cout <<endl;
    
    delete num;
    //free(num);-> c언어 version
    delete[] numArr;
    //free(numArr);-> c언어 version
  
    return 0 ;
}


 


C 언어의 malloc() / free(), C++ 언어의 new/ delete 은 메모리 부족을 유발할 수 있다. 그러므로 코드를 작성할 때 new 또는 malloc을 할 때마다 항상 delete 또는 free로 메모리에서 제거해줘야 한다.

 

 

memory layout (memory leak)- example

 

memory leak

 

memory leak

 

fct 함수에서 pnum 메모리 할당하였지만 fct 함수가 끝나기 전에 pnum의 메모리를 삭제하지 않아 메모리 heap 영역에 10의 변수 값이 남겨지게 된다.

 

memory leak