static variable

sujineeda·2021년 4월 1일
0

🤚C/C++

목록 보기
1/1
  • 정적변수는 프로그램이 종료되지 않는 이상 메모리 해제가 되지 않는다
  • 정적변수는 함수의 매개변수로 쓰일 수 없다.
    • 매개변수로 쓰이더라도 값이 유지되지 않아 정적 변수로서의 기능하지 못함
  • 초기화하지 않으면 0으로 초기화됨.

정적 변수의 이용

#동적 변수 사용시, 변수를 불러올 때마다 매번 생성되고 사라지므로 전에 데이터 저장 x
void increasenumber()
{
	int num1 = 0;
       	printf("%d\n", num1);
        num1++;
}
int main()
{
    increasenumber(); //0
    increasenumber(); //0
    increasenumber(); //0
    return 0;
}
#정적 변수 사용시, 프로그램이 종료되지 않는 이상 변수에 데이터가 그대로 남아 있음
void increasenumber()
{
	static int num1 = 0; //다시 함수가 호출될 때는 값 초기화 무시됨
       	printf("%d\n", num1);
        num1++;
}
int main()
{
    increasenumber(); //0
    increasenumber(); //1
    increasenumber(); //2
    return 0;
}

정적변수의 메모리 릭

#malloc하고 free 안해줘도 주소값만 잃지 않으면 메모리 누수 나지 않음
int main()
{
	static char *tmp;
    
    tmp = malloc(10);
    return (0)
}
#메모리를 잃었으므로 메모리 누수
int main()
{
	static char *tmp;
    
    tmp = malloc(10);
    tmp = 0;
    return (0);
}
profile
AD+AI Ph.D course

0개의 댓글