본문 바로가기
  • 책과 글
CS/운영체제

14. Interlude: Memory API

by twfnm67 2019. 11. 10.

14.1 Types of Memory

 - 두 가지 타입의 메모리가 있다

  1. stack 메모리(automatic 메모리) : 컴파일러에 의해 implicitly allocate & deallocate되는 메모리
void func(){
	int x; // declares an integer on the stack
	...
}

함수 리턴 시, 컴파일러는 메모리를 deallocate함

 

  2. heap 메모리 : 프로그래머가 직접 메모리를 allocate & deallocate

void func(){
	int *x=(int *)malloc(sizeof(int));
    ...
}

stack과 heap에 메모리 할당이 동시에 일어남. (the compiler knows to make room for a pointer to an integer when it sees (int *x), sebsequently, when the program calls malloc(), it requests space for an integer on the heap)

 

14.2 The malloc() Call

 - heap 공간을 얼만큼 할당 받을 것인지에 대한 size 정보를 malloc() 콜할 때에 전달한다.

 - succeed : 포인터에 새로 할당된 공간을 줌 / fail : NULL값

 

14.3 The free() Call

 

14.4 Common Errors

 - Forgetting To Allocate Memory

char *src = "hello";
char *dst;	//oops! unallocated
strcpy(dst, src);	//segfault and die
char *src = "hello";
char *dst = (char *)malloc(strlen(src)+1);
strcpy(dst, src);	//work properly

 - Not Allocating Enough Memory

char *src = "hello";
char *dst = (char *) malloc(strlen(src));	//too small!
strcpy(dst, src);	//work properly

 - Forgetting to Initialize Allocated Memory

 - Forgetting to Free Memory

 - Freeing Memory Before You Are Done With It

 - Freeing Memory Repeatedly

 - Calling free() Incorrectly

 

14.5 Underlying OS Support

 - malloc() and free() are not system calls, but rather library calls. Thus the malloc library manages space within your virtual address space, but itself is built on top of some system calls which call into the OS to ask for more memory or release some back to the system.

 

14.6 Other Calls

 - calloc()

 - realloc()

 

 

 

-출처-

<OPERATING SYSTEMS three easy pieces>

 

REMZI H. ARPACI-DUSSEAU

ANDREA C. ARPACI-DUSSEAU

UNIVERSITY OF WISCONSIN-MADISON

'CS > 운영체제' 카테고리의 다른 글

16. Segmentation  (0) 2019.11.23
15. Mechanism: Address Translation  (0) 2019.11.10
13. The Abstraction: Address Spaces  (0) 2019.11.08
12. A Dialogue on Memory Virtualization  (0) 2019.11.08
10. Multiprocessor Scheduling (Advanced)  (0) 2019.11.06

댓글