1 minute read

스택과 힙

shot2

#include <bits/stdc++.h> 
#define ll long long

using namespace std;


int main()
{
	ios::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);
	int a; //stack에 생성됨
	int* p;
	p = (int*)malloc(sizeof(int)); //힙에 생성
	*p = 10;
	p = (int*)malloc(sizeof(int)); //힙 다른주소에 또생성
    *p = 20;

	return 0;
}

이렇게 사용하면 사용하지 않는 공간이 힙에 남아있어서 메모리 낭비가댐.
그럼 메모리를 free시킵니다.

free(p);

#include <bits/stdc++.h> 
#define ll long long

using namespace std;


int main()
{
	ios::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);
	int a; //stack에 생성됨
	int* p;
	p = (int*)malloc(sizeof(int)); //힙에 생성
	*p = 10;
    free(p);
	p = (int*)malloc(sizeof(int)); //힙 다른주소에 또생성
    *p = 20;

	return 0;
}

free시키지 않는이상 힙에 동적할당한것은 전역변수와같은 라이프타임을 가집니다.
shot2

#include <bits/stdc++.h> 
#define ll long long

using namespace std;


int main()
{
	ios::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);
	int a; //stack에 생성됨
	int* p;
	p = (int*)malloc(sizeof(int));
	*p = 10;
	p = (int*)malloc(20*sizeof(int)); //20짜리 int 배열

	return 0;
}

C++에서의 동적할당 방법

#include <bits/stdc++.h> 
#define ll long long

using namespace std;


int main()
{
	ios::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);
	int a; //stack에 생성됨
	int* p;
	p = (int*)malloc(sizeof(int));
	*p = 10;
	p = (int*)malloc(20*sizeof(int)); //20짜리 int 배열

	return 0;
}

malloc calloc realloc

//malloc
int *p = (int*)malloc(sizeof(int)); //4byte
//동적할당을 바이트 만큼.
int *a = (int*)malloc*(4*sizeof(int)); //16byte
//calloc
int *c = (int*)calloc(4,sizeof(int)) //16byte
//int를 4개 저장할수 있는 만큼할당해줘라
realloc(a,20*sizeof(int))
//재할당할때 사용합니다.
//a를 80바이트로 재 할당 했습니다. 

Leave a comment