메모리 동적 할당:new와 delete

개발자는엉금엉금·2022년 10월 5일
0

따배cpp

목록 보기
1/8

new로 메모리 동적 할당하고 delete로 해제하기

#include <iostream>

using namespace std;

int main()
{
	int* ptr = new int(7);

	cout << *ptr << endl;

	delete ptr;
	ptr = nullptr;

	if (ptr != nullptr)
	{
		cout << ptr << endl;
		cout << *ptr << endl;
	}
    
    return 0;
}

  • new int() 또는 new int{}로 초기화가 가능하다
  • delete ptr;ptr = nullptr;은 같이 다닌다. 왜냐하면 할당한 메모리를 해제하면 ptr은 쓰레기값을 가리키는데, 이를 nullptr로 초기화하면 아무것도 가리키지 않아서 ptr은 0의 주소를 가진다.
  • if(ptr!=nullptr)로 포인터가 초기화되었는지 확인하자

인프런:따배씨++

0개의 댓글