패스트 캠퍼스 컴퓨터 공학 all in one 패키지. C
#include <stdio.h>
#include <stdlib.h>
int main(int argc, const char * argv[]) {
int *a = malloc(sizeof(int)); //sizeof(int)는 4바이트.
// 할당에 성공했다면 성공된 값을 a라는 변수에 넣겠다는 의미. 할당에 실패하면 null값이 들어감.
printf("%d\n",a);
a = malloc(sizeof(int));
printf("%d\n",a);
return 0;
}
결과
-1455400448
-1455400432

free()함수로 메모리 해제를 해주어야 한다.#include <stdio.h>
#include <stdlib.h>
int main(int argc, const char * argv[]) {
int *a = malloc(sizeof(int));
printf("%d\n",a);
free(a);
a = malloc(sizeof(int));
printf("%d\n",a);
free(a);
return 0;
}
결과
-2067768832
-2067768832
#include <stdio.h>
#include <stdlib.h>
int main(int argc, const char * argv[]) {
int** p = (int**)malloc(sizeof(int*) * 3);
for(int i = 0; i < 3; i++){
*(p+i) = (int*) malloc(sizeof(int) * 3);
}
for(int i=0; i < 3; i++){
for(int j=0; j < 3; j++){
*(*(p + i) + j) = i * 3 + j;
}
}
for( int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
printf("%d ", *(*(p + i) + j));
}
printf("\n");
}
return 0;
// 일반적으로 프로그램이 종료되는 순간, 프로그램 안에 사용되었던 모든 내용들은 다
// 메모리 해제가 이루어 지니깐, 이렇게 간단한 예제를 다룰 때에는 일일이 free()함수를 이용하지 않아도 된다.
// 하지만 실제 상용프로그램을 개발하고자 할 때는, 항상 free()함수를 이용해 메모리 해제를 해주어야 한다.
}
결과
0 1 2
3 4 5
6 7 8