SlideShare ist ein Scribd-Unternehmen logo
1 von 12
Downloaden Sie, um offline zu lesen
Dynamic Memory Allocation
2
Dynamic Memory Allocation
§ 동적 메모리 할당의 필요성
– 배열의 크기를 그 때 그 때 바꾸고 싶으면?
§ 동적 메모리 할당
– program의 수행 중 new storage를 할당하는 process
– stdlib.h에 함수 calloc()와 malloc()가 정의.
– calloc()은 인접한 할당 (contiguous allocation)을 의미
– malloc()은 메모리 할당 (memory allocation)을 의미.
malloc()과 calloc()을 사용한다.
3
Dynamic Memory Allocation
§ calloc()
– 각 원소가 object_size 바이트이고, 이 원소가 n개인 배열을
우해 메모리의 연속된 기억 공간을 할당한다.
– 각 원소는 0으로 초기화 된다.
– 호출이 성공하면 할당된 기억공간의 주소를 리턴한다.
– 호출이 성공하지 못하면 NULL을 리턴한다.
– Return type은 void*
calloc ( n, object_size );
size of each objectnumber of objects
4
Dynamic Memory Allocation
§ malloc()
– object_size의 바이트의 메모리 블록을 할당한다
– 초기화 시키지는 않는다.
– 호출이 성공하면 할당된 공간의 주소를 리턴한다.
– 호출이 성공하지 못하면 NULL을 리턴한다.
– Return type은 void*
malloc ( object_size );
size of each object
5
Dynamic Memory Allocation
§ 예제
#include <stdlib.h>
int main(void) {
char *p = (char*)malloc(26) ;
int k ;
for( k = 0 ; k < 26 ; k++ )
p[k] = ‘A’ + k ;
return 0;
}
#include <stdlib.h>
int main(void) {
char *p = (char*)calloc(26, 1) ;
int k ;
for( k = 0 ; k < 26 ; k++ )
p[k] = ‘A’ + k ;
return 0;
}
6
Dynamic Memory Allocation
§ 예제
#include <stdlib.h>
int main(void) {
int *p = (int*)malloc(26*4) ;
int k ;
for( k = 0 ; k < 26 ; k++ )
p[k] = k ;
return 0;
}
#include <stdlib.h>
int main(void) {
int *p = (int*)calloc(26, 4) ;
int k ;
for( k = 0 ; k < 26 ; k++ )
p[k] = k ;
return 0;
}
7
Dynamic Memory Allocation
§ free()
– malloc이나 calloc으로 할당된 메모리가 더 이상 필요 없으면
free를 사용하여 해지시킨다.
[Ex]
p = malloc(26);
…
free(p);
free를 호출하는 것은 p가
point하고 있는 memory
block를 해제하는 것이다.
void free(void *ptr);
8
Dynamic Memory Allocation
§ Dangling Pointer
– free한 포인터를 사용하면?
[Ex]
char *p = malloc(40) ;
free(p);
p[0] = ‘A’ ;
printf( “%cn”, p[0] ) ;
1000
40 bytes
1000
p
1000p
free(p)
???
9
Dynamic Memory Allocation
§ garbage
– 프로그램 내에서 calloc(), malloc()로 할당한 메모리 block 중
더 이상 필요 없는 것을 free하지 않고 그냥 놓아두면, 메모리
가 점점 모자라게 되어 결국 프로그램이 정상적으로 수행되
지 않는다.
– 이렇게 쓸 수 없게 된 memory block를 garbage라 한다.
while( 1 ) {
p = malloc( 100 ) ;
}
10
Dynamic Memory Allocation
§ garbage
int main()
{
int* p ;
p = malloc(100) ;
p = malloc(100) ;
…
}
1000
100 bytes
1000
p
2000
100 bytes
2000
p
100 bytes
1000
p =malloc(100)
11
Dynamic Memory Allocation
§ 임의 개수의 숫자를 입력 받아 역순으로 출력하기
int main() {
int k, p[20], num ; //array사용
while( 1 ) {
printf( “How many numbers?” ) ;
scanf( “%d”, &num ) ;
if( num < 0 ) break ;
for( k = 0 ; k < num ; k++ ) scanf( “%d”, &p[k] ) ;
for( k = num-1 ; k >= 0 ; k-- ) printf( “%d ”, p[k] ) ;
}
return 0;
}
12
Dynamic Memory Allocation
§ 임의 개수의 숫자를 입력 받아 역순으로 출력하기
int main() {
int k, *p, num ; //dynamic memory allocation사용
while( 1 ) {
printf( “How many numbers?” ) ;
scanf( “%d”, &num ) ;
if( num < 0 ) break ;
p = calloc( num, sizeof(int) ) ;
for( k = 0 ; k < num ; k++ ) scanf( “%d”, &p[k] ) ;
for( k = num-1 ; k >= 0 ; k-- ) printf( “%d ”, p[k] ) ;
free( p ) ;
}
return 0;
}

Weitere ähnliche Inhalte

Was ist angesagt?

Startup JavaScript 5 - 객체(Date, RegExp, Object, Global)
Startup JavaScript 5 - 객체(Date, RegExp, Object, Global)Startup JavaScript 5 - 객체(Date, RegExp, Object, Global)
Startup JavaScript 5 - 객체(Date, RegExp, Object, Global)Circulus
 
R 프로그래밍-향상된 데이타 조작
R 프로그래밍-향상된 데이타 조작R 프로그래밍-향상된 데이타 조작
R 프로그래밍-향상된 데이타 조작Terry Cho
 
Tensorflow regression 텐서플로우 회귀
Tensorflow regression 텐서플로우 회귀Tensorflow regression 텐서플로우 회귀
Tensorflow regression 텐서플로우 회귀beom kyun choi
 
2.Startup JavaScript - 연산자
2.Startup JavaScript - 연산자2.Startup JavaScript - 연산자
2.Startup JavaScript - 연산자Circulus
 
7가지 동시성 모델 - 데이터 병렬성
7가지 동시성 모델 - 데이터 병렬성7가지 동시성 모델 - 데이터 병렬성
7가지 동시성 모델 - 데이터 병렬성HyeonSeok Choi
 
[Pgday.Seoul 2021] 1. 예제로 살펴보는 포스트그레스큐엘의 독특한 SQL
[Pgday.Seoul 2021] 1. 예제로 살펴보는 포스트그레스큐엘의 독특한 SQL[Pgday.Seoul 2021] 1. 예제로 살펴보는 포스트그레스큐엘의 독특한 SQL
[Pgday.Seoul 2021] 1. 예제로 살펴보는 포스트그레스큐엘의 독특한 SQLPgDay.Seoul
 
Es2015 Simple Overview
Es2015 Simple OverviewEs2015 Simple Overview
Es2015 Simple OverviewKim Hunmin
 
Ji 개발 리뷰 (신림프로그래머)
Ji 개발 리뷰 (신림프로그래머)Ji 개발 리뷰 (신림프로그래머)
Ji 개발 리뷰 (신림프로그래머)beom kyun choi
 
Data Mining with R CH1 요약
Data Mining with R CH1 요약Data Mining with R CH1 요약
Data Mining with R CH1 요약Sung Yub Kim
 
7가지 동시성 모델 - 3장. 함수형 프로그래밍
7가지 동시성 모델 - 3장. 함수형 프로그래밍7가지 동시성 모델 - 3장. 함수형 프로그래밍
7가지 동시성 모델 - 3장. 함수형 프로그래밍Hyunsoo Jung
 
고등학생 R&E Python summary for test
고등학생 R&E Python summary for test고등학생 R&E Python summary for test
고등학생 R&E Python summary for testKyunghoon Kim
 
7가지 동시성 모델 4장
7가지 동시성 모델 4장7가지 동시성 모델 4장
7가지 동시성 모델 4장HyeonSeok Choi
 
R 프로그램의 이해와 활용 v1.1
R 프로그램의 이해와 활용 v1.1R 프로그램의 이해와 활용 v1.1
R 프로그램의 이해와 활용 v1.1happychallenge
 
Python Programming: Function
Python Programming: FunctionPython Programming: Function
Python Programming: FunctionChan Shik Lim
 
R 스터디 네번째
R 스터디 네번째R 스터디 네번째
R 스터디 네번째Jaeseok Park
 
React로 TDD 쵸큼 맛보기
React로 TDD 쵸큼 맛보기React로 TDD 쵸큼 맛보기
React로 TDD 쵸큼 맛보기Kim Hunmin
 
[Swift] Protocol (2/2)
[Swift] Protocol (2/2)[Swift] Protocol (2/2)
[Swift] Protocol (2/2)Bill Kim
 

Was ist angesagt? (20)

Startup JavaScript 5 - 객체(Date, RegExp, Object, Global)
Startup JavaScript 5 - 객체(Date, RegExp, Object, Global)Startup JavaScript 5 - 객체(Date, RegExp, Object, Global)
Startup JavaScript 5 - 객체(Date, RegExp, Object, Global)
 
함수적 사고 2장
함수적 사고 2장함수적 사고 2장
함수적 사고 2장
 
R 프로그래밍-향상된 데이타 조작
R 프로그래밍-향상된 데이타 조작R 프로그래밍-향상된 데이타 조작
R 프로그래밍-향상된 데이타 조작
 
Tensorflow regression 텐서플로우 회귀
Tensorflow regression 텐서플로우 회귀Tensorflow regression 텐서플로우 회귀
Tensorflow regression 텐서플로우 회귀
 
2.Startup JavaScript - 연산자
2.Startup JavaScript - 연산자2.Startup JavaScript - 연산자
2.Startup JavaScript - 연산자
 
7가지 동시성 모델 - 데이터 병렬성
7가지 동시성 모델 - 데이터 병렬성7가지 동시성 모델 - 데이터 병렬성
7가지 동시성 모델 - 데이터 병렬성
 
[Pgday.Seoul 2021] 1. 예제로 살펴보는 포스트그레스큐엘의 독특한 SQL
[Pgday.Seoul 2021] 1. 예제로 살펴보는 포스트그레스큐엘의 독특한 SQL[Pgday.Seoul 2021] 1. 예제로 살펴보는 포스트그레스큐엘의 독특한 SQL
[Pgday.Seoul 2021] 1. 예제로 살펴보는 포스트그레스큐엘의 독특한 SQL
 
Es2015 Simple Overview
Es2015 Simple OverviewEs2015 Simple Overview
Es2015 Simple Overview
 
Ji 개발 리뷰 (신림프로그래머)
Ji 개발 리뷰 (신림프로그래머)Ji 개발 리뷰 (신림프로그래머)
Ji 개발 리뷰 (신림프로그래머)
 
5. queue
5. queue5. queue
5. queue
 
R 시작해보기
R 시작해보기R 시작해보기
R 시작해보기
 
Data Mining with R CH1 요약
Data Mining with R CH1 요약Data Mining with R CH1 요약
Data Mining with R CH1 요약
 
7가지 동시성 모델 - 3장. 함수형 프로그래밍
7가지 동시성 모델 - 3장. 함수형 프로그래밍7가지 동시성 모델 - 3장. 함수형 프로그래밍
7가지 동시성 모델 - 3장. 함수형 프로그래밍
 
고등학생 R&E Python summary for test
고등학생 R&E Python summary for test고등학생 R&E Python summary for test
고등학생 R&E Python summary for test
 
7가지 동시성 모델 4장
7가지 동시성 모델 4장7가지 동시성 모델 4장
7가지 동시성 모델 4장
 
R 프로그램의 이해와 활용 v1.1
R 프로그램의 이해와 활용 v1.1R 프로그램의 이해와 활용 v1.1
R 프로그램의 이해와 활용 v1.1
 
Python Programming: Function
Python Programming: FunctionPython Programming: Function
Python Programming: Function
 
R 스터디 네번째
R 스터디 네번째R 스터디 네번째
R 스터디 네번째
 
React로 TDD 쵸큼 맛보기
React로 TDD 쵸큼 맛보기React로 TDD 쵸큼 맛보기
React로 TDD 쵸큼 맛보기
 
[Swift] Protocol (2/2)
[Swift] Protocol (2/2)[Swift] Protocol (2/2)
[Swift] Protocol (2/2)
 

Andere mochten auch

Week12 chapter11
Week12 chapter11 Week12 chapter11
Week12 chapter11 웅식 전
 
이펙티브 C++ 5,6 장 스터디
이펙티브 C++ 5,6 장 스터디이펙티브 C++ 5,6 장 스터디
이펙티브 C++ 5,6 장 스터디quxn6
 
Effective c++(chapter 5,6)
Effective c++(chapter 5,6)Effective c++(chapter 5,6)
Effective c++(chapter 5,6)문익 장
 
12장 상속 (고급)
12장 상속 (고급)12장 상속 (고급)
12장 상속 (고급)유석 남
 
이펙티브 C++ 공부
이펙티브 C++ 공부이펙티브 C++ 공부
이펙티브 C++ 공부quxn6
 
15 3. modulization
15 3. modulization15 3. modulization
15 3. modulization웅식 전
 
상속 관련 이것저것
상속 관련 이것저것상속 관련 이것저것
상속 관련 이것저것EG Lim
 
Responding to change
Responding to changeResponding to change
Responding to change기룡 남
 

Andere mochten auch (9)

Week12 chapter11
Week12 chapter11 Week12 chapter11
Week12 chapter11
 
이펙티브 C++ 5,6 장 스터디
이펙티브 C++ 5,6 장 스터디이펙티브 C++ 5,6 장 스터디
이펙티브 C++ 5,6 장 스터디
 
Effective c++(chapter 5,6)
Effective c++(chapter 5,6)Effective c++(chapter 5,6)
Effective c++(chapter 5,6)
 
12장 상속 (고급)
12장 상속 (고급)12장 상속 (고급)
12장 상속 (고급)
 
이펙티브 C++ 공부
이펙티브 C++ 공부이펙티브 C++ 공부
이펙티브 C++ 공부
 
15 3. modulization
15 3. modulization15 3. modulization
15 3. modulization
 
13. structure
13. structure13. structure
13. structure
 
상속 관련 이것저것
상속 관련 이것저것상속 관련 이것저것
상속 관련 이것저것
 
Responding to change
Responding to changeResponding to change
Responding to change
 

Mehr von 웅식 전

15 2. arguement passing to main
15 2. arguement passing to main15 2. arguement passing to main
15 2. arguement passing to main웅식 전
 
12 1. multi-dimensional array
12 1. multi-dimensional array12 1. multi-dimensional array
12 1. multi-dimensional array웅식 전
 
11. array & pointer
11. array & pointer11. array & pointer
11. array & pointer웅식 전
 
10. pointer & function
10. pointer & function10. pointer & function
10. pointer & function웅식 전
 
7. variable scope rule,-storage_class
7. variable scope rule,-storage_class7. variable scope rule,-storage_class
7. variable scope rule,-storage_class웅식 전
 
5 2. string processing
5 2. string processing5 2. string processing
5 2. string processing웅식 전
 
5 1. character processing
5 1. character processing5 1. character processing
5 1. character processing웅식 전
 
15 1. enumeration, typedef
15 1. enumeration, typedef15 1. enumeration, typedef
15 1. enumeration, typedef웅식 전
 
3 2. if statement
3 2. if statement3 2. if statement
3 2. if statement웅식 전
 
3 1. preprocessor, math, stdlib
3 1. preprocessor, math, stdlib3 1. preprocessor, math, stdlib
3 1. preprocessor, math, stdlib웅식 전
 
2 3. standard io
2 3. standard io2 3. standard io
2 3. standard io웅식 전
 
2 2. operators
2 2. operators2 2. operators
2 2. operators웅식 전
 
2 1. variables & data types
2 1. variables & data types2 1. variables & data types
2 1. variables & data types웅식 전
 
Goorm ide 교육용버전 for skku(학생)
Goorm ide 교육용버전 for skku(학생)Goorm ide 교육용버전 for skku(학생)
Goorm ide 교육용버전 for skku(학생)웅식 전
 
구름 기본 소개자료
구름 기본 소개자료구름 기본 소개자료
구름 기본 소개자료웅식 전
 
Goorm ide 소개 슬라이드(교육용 버전)
Goorm ide 소개 슬라이드(교육용 버전)Goorm ide 소개 슬라이드(교육용 버전)
Goorm ide 소개 슬라이드(교육용 버전)웅식 전
 

Mehr von 웅식 전 (20)

15 2. arguement passing to main
15 2. arguement passing to main15 2. arguement passing to main
15 2. arguement passing to main
 
14. fiile io
14. fiile io14. fiile io
14. fiile io
 
12 1. multi-dimensional array
12 1. multi-dimensional array12 1. multi-dimensional array
12 1. multi-dimensional array
 
11. array & pointer
11. array & pointer11. array & pointer
11. array & pointer
 
10. pointer & function
10. pointer & function10. pointer & function
10. pointer & function
 
9. pointer
9. pointer9. pointer
9. pointer
 
7. variable scope rule,-storage_class
7. variable scope rule,-storage_class7. variable scope rule,-storage_class
7. variable scope rule,-storage_class
 
6. function
6. function6. function
6. function
 
5 2. string processing
5 2. string processing5 2. string processing
5 2. string processing
 
5 1. character processing
5 1. character processing5 1. character processing
5 1. character processing
 
15 1. enumeration, typedef
15 1. enumeration, typedef15 1. enumeration, typedef
15 1. enumeration, typedef
 
4. loop
4. loop4. loop
4. loop
 
3 2. if statement
3 2. if statement3 2. if statement
3 2. if statement
 
3 1. preprocessor, math, stdlib
3 1. preprocessor, math, stdlib3 1. preprocessor, math, stdlib
3 1. preprocessor, math, stdlib
 
2 3. standard io
2 3. standard io2 3. standard io
2 3. standard io
 
2 2. operators
2 2. operators2 2. operators
2 2. operators
 
2 1. variables & data types
2 1. variables & data types2 1. variables & data types
2 1. variables & data types
 
Goorm ide 교육용버전 for skku(학생)
Goorm ide 교육용버전 for skku(학생)Goorm ide 교육용버전 for skku(학생)
Goorm ide 교육용버전 for skku(학생)
 
구름 기본 소개자료
구름 기본 소개자료구름 기본 소개자료
구름 기본 소개자료
 
Goorm ide 소개 슬라이드(교육용 버전)
Goorm ide 소개 슬라이드(교육용 버전)Goorm ide 소개 슬라이드(교육용 버전)
Goorm ide 소개 슬라이드(교육용 버전)
 

12 2. dynamic allocation

  • 2. 2 Dynamic Memory Allocation § 동적 메모리 할당의 필요성 – 배열의 크기를 그 때 그 때 바꾸고 싶으면? § 동적 메모리 할당 – program의 수행 중 new storage를 할당하는 process – stdlib.h에 함수 calloc()와 malloc()가 정의. – calloc()은 인접한 할당 (contiguous allocation)을 의미 – malloc()은 메모리 할당 (memory allocation)을 의미. malloc()과 calloc()을 사용한다.
  • 3. 3 Dynamic Memory Allocation § calloc() – 각 원소가 object_size 바이트이고, 이 원소가 n개인 배열을 우해 메모리의 연속된 기억 공간을 할당한다. – 각 원소는 0으로 초기화 된다. – 호출이 성공하면 할당된 기억공간의 주소를 리턴한다. – 호출이 성공하지 못하면 NULL을 리턴한다. – Return type은 void* calloc ( n, object_size ); size of each objectnumber of objects
  • 4. 4 Dynamic Memory Allocation § malloc() – object_size의 바이트의 메모리 블록을 할당한다 – 초기화 시키지는 않는다. – 호출이 성공하면 할당된 공간의 주소를 리턴한다. – 호출이 성공하지 못하면 NULL을 리턴한다. – Return type은 void* malloc ( object_size ); size of each object
  • 5. 5 Dynamic Memory Allocation § 예제 #include <stdlib.h> int main(void) { char *p = (char*)malloc(26) ; int k ; for( k = 0 ; k < 26 ; k++ ) p[k] = ‘A’ + k ; return 0; } #include <stdlib.h> int main(void) { char *p = (char*)calloc(26, 1) ; int k ; for( k = 0 ; k < 26 ; k++ ) p[k] = ‘A’ + k ; return 0; }
  • 6. 6 Dynamic Memory Allocation § 예제 #include <stdlib.h> int main(void) { int *p = (int*)malloc(26*4) ; int k ; for( k = 0 ; k < 26 ; k++ ) p[k] = k ; return 0; } #include <stdlib.h> int main(void) { int *p = (int*)calloc(26, 4) ; int k ; for( k = 0 ; k < 26 ; k++ ) p[k] = k ; return 0; }
  • 7. 7 Dynamic Memory Allocation § free() – malloc이나 calloc으로 할당된 메모리가 더 이상 필요 없으면 free를 사용하여 해지시킨다. [Ex] p = malloc(26); … free(p); free를 호출하는 것은 p가 point하고 있는 memory block를 해제하는 것이다. void free(void *ptr);
  • 8. 8 Dynamic Memory Allocation § Dangling Pointer – free한 포인터를 사용하면? [Ex] char *p = malloc(40) ; free(p); p[0] = ‘A’ ; printf( “%cn”, p[0] ) ; 1000 40 bytes 1000 p 1000p free(p) ???
  • 9. 9 Dynamic Memory Allocation § garbage – 프로그램 내에서 calloc(), malloc()로 할당한 메모리 block 중 더 이상 필요 없는 것을 free하지 않고 그냥 놓아두면, 메모리 가 점점 모자라게 되어 결국 프로그램이 정상적으로 수행되 지 않는다. – 이렇게 쓸 수 없게 된 memory block를 garbage라 한다. while( 1 ) { p = malloc( 100 ) ; }
  • 10. 10 Dynamic Memory Allocation § garbage int main() { int* p ; p = malloc(100) ; p = malloc(100) ; … } 1000 100 bytes 1000 p 2000 100 bytes 2000 p 100 bytes 1000 p =malloc(100)
  • 11. 11 Dynamic Memory Allocation § 임의 개수의 숫자를 입력 받아 역순으로 출력하기 int main() { int k, p[20], num ; //array사용 while( 1 ) { printf( “How many numbers?” ) ; scanf( “%d”, &num ) ; if( num < 0 ) break ; for( k = 0 ; k < num ; k++ ) scanf( “%d”, &p[k] ) ; for( k = num-1 ; k >= 0 ; k-- ) printf( “%d ”, p[k] ) ; } return 0; }
  • 12. 12 Dynamic Memory Allocation § 임의 개수의 숫자를 입력 받아 역순으로 출력하기 int main() { int k, *p, num ; //dynamic memory allocation사용 while( 1 ) { printf( “How many numbers?” ) ; scanf( “%d”, &num ) ; if( num < 0 ) break ; p = calloc( num, sizeof(int) ) ; for( k = 0 ; k < num ; k++ ) scanf( “%d”, &p[k] ) ; for( k = num-1 ; k >= 0 ; k-- ) printf( “%d ”, p[k] ) ; free( p ) ; } return 0; }