C - malloc_ c 메모리 동적할당
// Memory allocation
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
int iInput, iMax;
int *iStudent = NULL;
fputs("Please enter the max number of array :", stdout);
scanf_s("%d", &iMax);
iStudent = (int *)malloc(iMax * sizeof(int));
for (int i = 0; i < iMax; ++i)
{
printf_s("%2d 번 학생의 점수 입력 : ",i+1);
scanf_s("%d", &iInput);
iStudent[i] = iInput;
}
for (int i = 0; i < iMax; ++i)
{
printf_s("%2d 번 학생의 점수: %4d\n", i+1, iStudent[i]);
}
printf_s("before_free = %p\t", iStudent);
printf_s("before_free_size = %d\n", sizeof(iStudent));
free(iStudent); // 메모리 해제
printf_s("after_free = %p\t", iStudent);
printf_s("after_free_size = %d\n", sizeof(iStudent));
iStudent[0] = 0; // BUG : 메모리 주소가 남아 있어서 에러 발생안함
iStudent = NULL; // 메모리주소를 NULL로 초기화
printf_s("after_NULL = %p\t", iStudent);
printf_s("after_free_size = %d\n", sizeof(iStudent));
iStudent[0] = 0; // 메모리 주소가 NULL이기 때문에 에러 발생
free(iStudent); // 메모리 주소가 NULL이기 때문에 에서 발생 안함
//return 0;
}
'my_lesson > _C' 카테고리의 다른 글
C - Input output 표준 입출력 (0) | 2019.03.08 |
---|---|
9. C_lesson 3차원 배열이 매개변수로 사용된 함수 (0) | 2014.04.07 |
8. C_lesson 단항 연산자 !not,~비트not,+,- (0) | 2013.10.09 |
7. C_lesson 별로만든 뒤집어진 트리 program (0) | 2013.09.29 |
6. C_lesson 별로만든 트리 program (0) | 2013.09.29 |
댓글