새로 만들기/삭제
new 연산자는 힙에 메모리 할당을 요청합니다. 사용 가능한 메모리가 충분하면 포인터 변수에 메모리를 초기화하고 해당 주소를 반환합니다.
삭제 연산자는 메모리 할당을 해제하는 데 사용됩니다. 사용자는 이 삭제 연산자에 의해 생성된 포인터 변수의 할당을 해제할 수 있는 권한이 있습니다.
다음은 C++ 언어의 새/삭제 연산자의 예입니다.
예시
#include <iostream>
using namespace std;
int main () {
int *ptr1 = NULL;
ptr1 = new int;
float *ptr2 = new float(299.121);
int *ptr3 = new int[28];
*ptr1 = 28;
cout << "Value of pointer variable 1 : " << *ptr1 << endl;
cout << "Value of pointer variable 2 : " << *ptr2 << endl;
if (!ptr3)
cout << "Allocation of memory failed\n";
else {
for (int i = 10; i < 15; i++)
ptr3[i] = i+1;
cout << "Value of store in block of memory: ";
for (int i = 10; i < 15; i++)
cout << ptr3[i] << " ";
}
delete ptr1;
delete ptr2;
delete[] ptr3;
return 0;
} 출력
다음은 출력입니다.
Value of pointer variable 1 : 28 Value of pointer variable 2 : 299.121 Value of store in block of memory: 11 12 13 14 15
malloc/무료
malloc() 함수는 요청된 바이트 크기를 할당하는 데 사용되며 할당된 메모리의 첫 번째 바이트에 대한 포인터를 반환합니다. 실패하면 null 포인터를 반환합니다.
free() 함수는 malloc()에 의해 할당된 메모리를 할당 해제하는 데 사용됩니다. 포인터의 값은 변경되지 않으므로 여전히 동일한 메모리 위치를 가리킵니다.
다음은 C 언어로 된 malloc/free의 예입니다.
예시
#include <stdio.h>
#include <stdlib.h>
int main() {
int n = 4, i, *p, s = 0;
p = (int*) malloc(n * sizeof(int));
if(p == NULL) {
printf("\nError! memory not allocated.");
exit(0);
}
printf("\nEnter elements of array : ");
for(i = 0; i < n; ++i) {
scanf("%d", p + i);
s += *(p + i);
}
printf("\nSum : %d", s);
free(p);
return 0;
} 출력
다음은 출력입니다 -
Enter elements of array : 32 23 21 8 Sum : 84