strtok를 이용한 후, strcpy를 하였을 때, 쓰레기 값 발생문제
아래와 같이 Source를 참고하여 보자.
int SUI_ToolControl_Get_DNS(void)
{
FILE *fp = fopen("/etc/resolv.conf", "rb");
char DNS_AA[20];
char s1[] = "dd";
char s2[] = " ";
char temp[] = " ";
char* token = NULL;
int i = 0;
if(fp == NULL)
{
printf("DNS /etc/resolv.conf file error\n");
return -1;
}
while(fgets(DNS_AA, 100, fp) != NULL)
{
strcpy(s1, DNS_AA);
i++;
}
token = strtok(s1, s2);
while(token != NULL)
{
printf("token = %s\n", token);
strcpy(temp, token);
token = strtok(NULL, s2);
}
printf("%s\n", temp);
int dd = strlen(temp)-1;
strncpy(SUI_Net_Info.SUI_NetDNS, temp, dd);
return 0;
}
위와 같이 빨간색으로 나와 있는 부분처럼 temp의 전체 크기를 읽어드린 후, -1을 하게 되면은 쓰레기값은 발생하지 않는다.