[C++] new & delete

KWANHO PARK·2025년 3월 18일

CPP

목록 보기
4/24

malloc & free

  • C언어에서 heap 메모리 동적 할당 및 소멸 함수
    ex)
/*
길이 정보를 인자로 받아서, 해당 길이의 문자열 저장이 가능한 배열 생성, 해당 배열의 주소값 반환하는 함수
*/
#include <iostream>
#include <string.h>
#include <stdlib.h>
using namespace std;

char* makeStrAddr(int len) {
	char* str = (char*)malloc(sizeof(char)*len); // heap영역에 입력크기만큼 메모리 공간을 할당받아서 시작 주소 return 
    return str;
}

int main()
{
	char* str = makeStrAddr(20);
    strcpy(str, "9 to 24 everyday.");
    cout << str << endl;
    free(str);
	return 0;
}
  • 단점
    - 할당 대상의 정보를 무조건 바이트 크기 단위로 전달해야 함
    • 반환형이 void형 포인터라서 형변환 필요

new & delete

  • malloc & free 함수의 단점 제거

사용법

  1. new
  • int형 변수 할당
int* ptr1 = new int;
  • double형 변수 할당
double* ptr2 = new double;
  • ex) 길이가 3인 int형 배열 할당
int* arr1 = new int[3];
  • ex) 길이가 7인 double형 배열 할당
double* arr2 = new double[7];
  1. delete
  • 할당한 int형 변수 소멸
delete ptr1;
  • 할당한 double형 변수 소멸
delete ptr2;
  • 할당한 int형 배열 소멸
delete []arr1;
  • 할당한 double형 배열 소멸
delete []arr2;

ex)

#include <iostream>
#include <string.h>
#include <stdlib.h>
using namespace std;

char* makeStrAddr(int len) {
	// char* str = (char*)malloc(sizeof(char)*len); // heap영역에 입력크기만큼 메모리 공간을 할당받아서 시작 주소 return 
    char* str = new char[len];
    return str;
}

int main()
{
	char* str = makeStrAddr(20);
    strcpy(str, "9 to 24 everyday.");
    cout << str << endl;
    // free(str);
    delete []str;
	return 0;
}

객체 생성시 반드시 new & delete

  • 객체 생성시 malloc & free 함수의 문제점
#include <iostream>
#include <stdlib.h>
using namespace std;

class Simple {
public:
	Simple()
    {
    	cout << "I'm simple constructor!" << endl;
    }
};

int main()
{
	cout << "case 1: ";
    Simple *sp1 = new Simple;	// new 연산자 이용해서 heap 영역에 변수 할당
    
    cout << "case 2: ";
    Simple *sp2 = (Simple*)malloc(sizeof(Simple)*1); // malloc 함수 이용해서 heap 영역에 변수 할당
    
    cout << endl << "end of main" << endl;
    delete sp1;
    free(sp2);
	return 0;
}

-> Simple *sp1 = new Simple; 실행 결과로 I'm simple constructor!가 출력되었지만, Simple *sp2 = (Simple*)malloc(sizeof(simple)*1);의 결과는 나오지 않음.
new와 malloc 함수의 동작 방식에 차이 존재

포인터 사용하지 않고 heap에 할당된 변수 접근 가능

  • 참조자 선언은 const 참조자를 제외하고 변수 대상으로만 가능
  • new 연산자 이용해서 할당된 메모리 공간에 참조자 선언
    - new 연산자 이용해서 할당된 메모리 공간도 변수로 간주
    -> 참조자 선언 가능
int *ptr = new int;
int &ref = *ptr;	// heap 영역에 할당된 변수에 대한 참조자 선언
ref = 20;
cout << *ptr << endl;

-> 출력 결과 : 20


실습 코드

/*
	메모리 동적 할당: new - delete(C에서의 malloc-free)
	자료형 포인터 = new 자료형(크기)
	new는 생성자를 호출한다. 즉 new는 객체를 생성시킨다.
	객체를 생성하기 위해서는 생성자 호출이 있어야 한다.
*/

#include <iostream>
using namespace std;
//C++ 스타일
int main()
{
	int size;
	int* pary;

	//int* pn = new int;	힙영역에 int크기로 동적 할당을 받는다.
	//delete pn;

	cout << "크기>> ";
	cin >> size;

	pary = new int[size];
	pary[0] = 1;
	pary[1] = 2;
	*(pary + 2) = 3;

	cout << pary[0] << ", " << pary[1] << ", " << *(pary + 2) << endl;
	delete[] pary;

	return 0;
}

/*
	new는 생성자 호출이 되므로 초기화 가능
	생성자 - 객체를 생성, 초기화하는 특별한 메서드
*/

#include <iostream>
using namespace std;

int main()
{
	int* parr;
	parr = new int[3] {10, 20, 30};			// 이름없는 배열객체 생성하고 10, 20, 30으로 초기화
	// parr = new int[3] = {10, 20, 30};

	cout << parr[0] << ", " << parr[1] << ", " << parr[2] << endl;
	delete[] parr;

	return 0;
}

0개의 댓글