11. [C++] malloc & free를 대신하는 new & delete

2024. 4. 11. 16:41[C++]/C++ 언어 기초

사전 지식
  • 힙(Heap) 자료구조
  • 메모리 할당에 사용하는 malloc과 free

🍃  new & delete

 

malloc과 free를 사용한 힙 영역의 할당

#include "stdafx.h"
#include <iostream>
#include <stdlib.h>

using namespace std;
using namespace System;

char * MakeStrAdr(int len){
	char *str = (char*)malloc(sizeof(char)*len); //문자열 저장을 위한 배열을 힙 영역에 할당
	return str;
}

int main(void)
{
	char *str = MakeStrAdr(20);
	strcpy(str, "I'm so happy"); //문자열을 str 변수에 복사 
        cout<<str<<endl;
	free(str); //힙에 할당된 메모리 공간을 소멸
	return 0;
}


/*참고
strcpy 함수란?
char* strcpy(char* dest, const char* origin);
origin에 있는 문자열 전체를 dest로 복사 하는 함수
*/

 

위 예제는 C언어에서의 동적할당을 보이기 위한 것이다. 이 방법에는 두 가지 불편 사항이 따른다.

  • 할당할 대상의 정보를 무조건 바이트 크기단위로 전달해야 한다.
  • 반환형이 void형 포인터이기 때문에 적절한 형 변환을 거쳐야 한다.

 

 

🍃  C++에서 제공하는 키워드 new와 delete를 사용하면 이러한 불편한 점이 사라진다.

malloc -> new
free -> delete

1) new 사용 방법

- int형 변수의 할당			int *ptr1 = new int;
- double형 변수의 할당			double *ptr2 = new double;
- 길이가 3인 int형 배열의 할당		int *arr1 = new int[3];
- 길이가 7인 double형 배열의 할당		double *arr2 = new double[7];

2) delete 사용 방법

- int형 변수의 소멸			int *ptr1 = delete ptr1;
- double형 변수의 소멸			double *ptr2 = delete ptr2;
- 길이가 3인 int형 배열의 소멸		int *arr1 = delete []arr1;
- 길이가 7인 double형 배열의 소멸		double *arr2 = delete []arr2

 

new와 delete를 사용한 힙 영역의 할당 예제

#include <iostream>
#include <string.h>

using namespace std;

char * MakeStrAdr(int len)
{
    // char * str = (char*)malloc(sizeof(char)*len);
    char * str = new char[len];
    return str;
}

int main(void)
{
    char * str = MakeStrAdr(20);
    strcpy(str, "I am so happy~");
    cout<<str<<endl;
    // free(str);
    delete []str;
    return 0;
}

 

 

🍃 객체의 생성에는 반드시 new & delete

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

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

int main(void)
{
    cout<<"case 1: ";
    Simple *sp1 = new Simple; // new 연산자로 힙 영역에 변수 할당

    cout<<"case 2: ";
    Simple * sp2 = (Simple*)malloc(sizeof(Simple)*1); // malloc 함수를 통해 힙 영역에 변수 할당

    cout<<endl<<"end of main"<<endl;
    delete sp1; 	// 소멸
    free(sp2); 		// 소멸
    return 0;
}

 

new와 malloc 함수의 동작 방식에는 차이가 있다.

 

  • case 1은 new로 힙 영역에 메모리를 할당해준다. 또한, 실행의 결과로 I'm simple constructor!가 출력되었다.
  • case 2는 malloc으로 힙 영역에 메모리를 할당해준다. 실행의 결과로 어떠한 문자열의 출력도 없다.

 

 

🍃 힙에 할당된 변수, 포인터를 사용하지 않아도 접근할 수 있다.

  • 참조자의 선언상수가 아닌 변수를 대상으로만 가능하다.(const 참조자가 아닌 경우)

new 연산자를 이용해서 할당된 메모리 공간에 참조자 선언이 가능할까?

  • C++에서는 new 연산자를 이용해서 할당된 메모리 공간도 변수로 간주하여, 참조자의 선언이 가능하도록 하고 있다.
int *ptr = new int;
int &ref = *ptr;		// 힙 영역에 할당된 변수에 대한 참조자 선언
ref = 20;
cout<<*ptr<<endl;		// 출력 결과는 20

 

 


Quiz

 

2차원 평면상에서 좌표를 표현할 수 있는 구조체를 다음과 같이 정의하였다.

typedef struct __Point
{
	int xPos;
	int yPos;
} Point;

 

위의 구조체를 기반으로 두 점의 합을 계산하는 함수를 다음의 형태로 정의하고 있을 때, 임의의 두 점을 선언하여 함수를 이용한 덧셈연산을 진행하는 main함수를 정의해보자.

Point& PntAdder(const Point &p1, const Point &p2);

 

 

풀이

#include "stdafx.h"
#include <iostream>
#include <stdlib.h>

using namespace std;

typedef struct __Point{
	int xpos;
	int ypos;
} Point;

Point& PntAdder(const Point &p1, const Point &p2){
	Point * ptr= new Point;
	
	ptr -> xpos = p1.xpos + p2.xpos;
	ptr -> ypos = p1.ypos + p2.ypos;

	return *ptr;
};


int main(void)
{
	Point *pptr1 = new Point;
	pptr1->xpos = 10;
	pptr1->ypos = 20;

	Point *pptr2 = new Point;
	pptr2->xpos = 20;
	pptr2->ypos = 30;

	Point &ref = PntAdder(*pptr1, *pptr2);

	cout << "두 점의 합 : (" << ref.xpos << ", " << ref.ypos << ")" << endl;

	return 0;
}

 

 


참고 자료

 

동적 할당과 malloc, free란?

https://velog.io/@youngeui_hong/C-%EC%96%B8%EC%96%B4-%EA%B8%B0%EC%B4%88-%EB%8F%99%EC%A0%81-%EB%A9%94%EB%AA%A8%EB%A6%AC-%ED%95%A0%EB%8B%B9-malloc%EA%B3%BC-free-%ED%95%A8%EC%88%98

 

[C 언어 기초] 동적 메모리 할당: malloc과 free 함수

동적 메모리 할당에 대해 알아보자! 🤓

velog.io

 

힙 자료구조란?

https://todaycode.tistory.com/56

 

힙(Heap) 이란?

1. 힙(Heap) 1-1. 힙이란? 1-2. 힙의 종류 1-3. 힙의 활용 1-4. 예시(힙 삽입) 1. 힙(Heap) 1-1. 힙이란? 맨 처음에 힙을 들었을 때 엉덩이(hip)가 생각날 수도 있지만 힙은 heap이다. 무언가를 차곡차곡 쌓아 올

todaycode.tistory.com

반응형