728x90

Type of Memory


In running a C program, there are two types of memory that are allocated.

  • Stack memory: The allocations of deallocations of it are mangaged implicitly by compiler for a programmer(so called as automatic memory).

A stack frame stores return address, function parameters, and tempral variables etc.

  • Heap memory: The allocations and deallocations are explicitly handled by the programmer.
void func() {
    int *x = (int *)malloc(sizeof(int));
    ...
}

malloc() 함수


malloc() 호출은 매우 간단하다. Heap에 요철할 공간의 크기를 넘겨 주면, 성공했을 경우 새로 할당된 공간에 대한 포인터를 사용자에게 반환하고 실패할 경우 NULL을 반환한다.

#include <stdlib.h>
...
void *malloc(size_t size);
double *d = (double *) malloc(sizeof(double));
int *x = malloc(10 * sizeof(int));
주의-- 필요로 하는 저장공간을 정확하게 입력 해줘야함. 특히 string
-> 시스템에서 각각의 연산자와 몇 byte를 사용하는지 어떻게 알까? -> 그래서 sizeof()를 사용.

free() call


To free heap memory that is no longer in use, programmers simply call free().

int *x = malloc(10* siezof(int));
...
free(x);

Automatic memory management

With such a facility, a programmer calls something akin to malloc() to allocate memory (usually new) but never have to call something to free space. ← 다른 언어들.

A garbage collector runs after and figures out what memory you no longer have references to and frees it.

JAVA로 구현한 것이 별도의 부하가 발생. Memroy translation, java virtual machine에서 동작하기 때문. 즉 JAVA는 java virtual machine이라는 별도의 부하가 존재하고 이 내에서는 또 Garbage Collector가 돌아다니면서 resource들을 먹고 있기 때문에 C로 구현했을때보다 느리다.

Common Errors

JAVA, C etc .. → stack overflow
C, C++ → segmentation fault 발생.

 

 

Forgetting to allocate memory

char *src = "hello";
char *dst; // oops! unallocated
strcpy(dst, src); // segfaut and die

 

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 → Memory leak

Freeing memory befroe you are done with it.

Freeing memory repeatedly

Calling free() incorrectly in(부) correct

Two levels of memory management


The first level of memory management is performed by the OS, which hands out memory to processes when they run, and takes it back when process exit (or otherwise die).

The second level of management is within each process, for example within the heap when you call malloc() and free().

Even if a programmer fails to call free(), the OS will reclaim all the memory of the processes when the program is finished running.

반응형

+ Recent posts