Programming/C++
C++ 메모리 동적 할당, 동적 할당 배열
Ryuha류하
2021. 3. 15. 00:35
메모리를 새로 할당하고 제거할때 이러한 코드들을 작성한다.
#include <iostream>
using namespace std;
int main()
{
// new int 는 int 사이즈만큼 메모리 받아오고
// 그 주소를 알려줌 그래서 포인터로 받아야 한다.
int *ptr = new int(7);
cout << ptr << endl;
cout << *ptr << endl;
//프로그램이 끝나기 전에 미리 반납하는 것
delete ptr;
// nullptr은 아무 의미 없다는거 기록 하는 것
ptr = nullptr;
//ptr이 null이 아닐때만 cout을 실행함
if (ptr != nullptr)
{
cout << ptr << endl;
cout << *ptr << endl;
}
else
{
cout << "Could not allocate memory" << endl;
}
return 0;
}
메모리 누수
메모리를 반복적으로 생성하지만 delete를 안해주었을 때 나타나는 현상이다.
#include <iostream>
using namespace std;
int main()
{
// memory leak
//메모리를 사용하고 제거하는게 아니라 계속 쓰는거임
while (true)
{
int *ptr = new int;
cout << ptr << endl;
}
return 0;
}
동적 할당 배열
#include <iostream>
using namespace std;
int main()
{
int length;
cin >> length;
int *array = new int[length](); //0으로 초기화 ()
array[0] = 1;
array[1] = 2;
for (int i = 0; i < length; i++)
{
cout << (uintptr_t)&array[i] << endl;
cout << array[i] << endl;
}
delete[] array;
return 0;
}