2015년 8월 25일 화요일

C 언어 - 초기화

값의 초기화


C 언어는 개발자를 대신해서 값을 초기화 하지 않는다.

#include <stdio.h>
void foo() {
    int a;
    printf("%d\n", a);
}
int main() {
    int a;
    printf("%d\n", a);
    foo();
    return 0;
}

실행
0
32672

컴파일러 warning

 initialize.c: In function ‘foo’:
 initialize.c:10:8: warning: ‘a’ is used uninitialized in this function [-Wuninitialized]
   printf("%d\n", a);
         ^

초기화 하지 않고 변수를 사용하게 되면 의도치 않는 실행 결과를 가져올 수 있기 때문에 컴파일러 차원에서도 경고를 표시한다.

값 초기화 하기


일반 변수 및 배열 초기화


char * str = NULL;
int number = 0;
char array[64] = {0,};

struct 초기화


struct person_t {
    char name[128];
    int age;
};
struct person_t person = {{0,}, 0};

명시적 방법

struct peson_t person = {
    .name = {0,},
    .age = 0
};

heap 메모리 초기화


str = (char*)malloc(24);
memset(str, 0, 24);

memset


memset 은 메모리를 초기화하는 표준 API 이다. (stdlib.h)
http://www.cplusplus.com/reference/cstring/memset/

void * memset(void * ptr, int value, size_t num);

파라메터

  • ptr : 초기화하려는 메모리 포인터
  • value : 초기화 값
  • num : 메모리 크기

리턴 값

  • void * : ptr 값이 리턴됨



댓글 없음:

댓글 쓰기