본문 바로가기

C++

[C++] 메모리 동적 할당 new와 delete 연산자

C언어에서 malloc()과 free()가 있다면 C++문법에는 new와 delete 연사자가 있다.

 

new와 delete는 C++에서 객체를 동적 할당하고 해제하는 연산자이다. 예는 다음과 같다.

 

int *x = new int;
delete x;

 

배열의 경우 다음과 같이 사용할 수 있다.

 

int *y = new int[10];
delete[] y;

 

 

new 연산자는 malloc() 함수와 달리 메모리 크기를 정하지 않아도 된다.

 

#include <iostream>
using namespace std;

int main()
{
	//메모리 동적 할당과 초기화
	int* pNew = new int(10);
	cout << *pNew << endl;

	*pNew = 100;
	cout << *pNew << endl;
    
	delete pNew;	//해제

	return 0;
}

 

결과값:

10
100

 

 

한편, 메모리 동적 할당 사용 시 주의해야 할 점이 있다.

 

#include <iostream>
using namespace std;

int main()
{
	int* ptr1, * ptr2;

	ptr1 = new int;
	*ptr1 = 10;
	ptr2 = new int;
	ptr2 = ptr1;	//ptr1과 ptr2는 같은 주소

	delete ptr1;
	delete ptr2;	//에러

	return 0;
}

 

결과값:

에러, 프로그램종료

 

예제 실행 시 에러가 발생하면서 프로그램이 종료된다. ptr1과 ptr2는 주소가 같은데 ptr1 주소를 이미 delete 했지만 다시 delete 했기 때문이다.

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

[C++] 변환 생성자의 묵시적 변환과 임시 객체 explicit  (0) 2019.12.18
[C++] 복사 생성자(copy constructor)  (0) 2019.12.17
[C++] 생성자와 소멸자  (0) 2019.12.16
[C++] 참조자(Reference)  (0) 2019.12.16
[C++] this 포인터  (0) 2019.12.15