더블포인터 질문드려요
글쓴이: yeonjooo / 작성시간: 일, 2015/09/27 - 2:11오후
필요 없는 부분은 생략한 코드입니다. 주석문 부분만 봐주세요~
//구조체 선언 부분
#define BUF_SIZE 2500
typedef struct cmd_{
char *id;
char *action;
char *pipe_id;
char *command;
}cmd;
int main (int argc, char **argv){
//error:don't put configuration file
if (argc <= 1)
{
fprintf (stderr, "configuration file must specified\n");
return -1;
}
char *fileName=argv[1];
char *str=(char*)malloc(sizeof(char)*BUF_SIZE);//buffer that save one command line
FILE *fp;
int cmd_count=0;//line number variable
if((fp=fopen(fileName,"r"))==NULL){
fprintf (stderr, "failed to load config file %s \n", fileName);
return -1;
}
while(!feof(fp)){
cmd_count++;
fgets(str,BUF_SIZE,fp);
if((str[0]!='#')&&(str[0]!='\n')){
int i=0,invalid_cmd=0,err_result=0;
err_result=check_err(str);
if(err_result==1)
fprintf (stderr, "invalid format in line%d ,ignored \n", cmd_count);
else{
printf("%s",str);
//cmd 구조체를 넘기는 부분
cmd *newCmd;
changeToStruct(str,&newCmd);
printf(" id=%s action=%s pipe_id=%s ",newCmd->id,newCmd->action,newCmd->pipe_id);
printf("command=%s\n",newCmd->command);
}
}
}
free(str);
fclose(fp);
return 0;
}
//str을 구조체로 변환하는 부분
void changeToStruct(char *str,cmd**dst){//temporary void original cmd
cmd newCmd;
char *buf=str;
char **bufSection=(char**)malloc(sizeof(char*)*4);
int i=0,j=0;
//구분자를 기준으로 하여 str을 나눈 다음 bufSection[j]에 넣는 부분
for(;j<3;j++){
bufSection[j]=(char*)malloc(sizeof(char)*BUF_SIZE);
while(buf[i]==' ')
i++;
if(buf[i]==':'){
strcpy(bufSection[j],"no");
i++;
}
else{
strcpy(bufSection[j],strtok(buf,":"));
i=strlen(bufSection[j])+1;//1->delim
}
buf=&buf[i];
i=0;
}
//여기부터 문제입니다ㅠㅠ
*dst=(cmd*)calloc(sizeof(cmd),sizeof(char));
strncpy((*dst)->id,bufSection[0],strlen(bufSection[0]));
strncpy((*dst)->action,bufSection[1],strlen(bufSection[1]));
strncpy((*dst)->pipe_id,bufSection[2],strlen(bufSection[2]));
while(buf[i]==' ')
i++;
if(buf[i+1]=='\0')
strncpy((*dst)->command,"no",strlen("no"));
else
strncpy((*dst)->command,buf,strlen(buf));
for(j=0;j<3;j++)
free(bufSection[j]);
free(bufSection);
return;
}bufSection값들은 정상으로 들어갑니다. 원래는 걍 배정문으로 해서 넣었는데 free()하면서 쓰레기값이 들어가더라구요.물론 함수가 끝나도 마찬가지겠지만. 그래서 strncpy함수를 썼는데, 배정문으로 할때는 되던게 segmentation fault가 뜨네요. 도와주시면 정말 감사하겠습니다!
Forums:


문자열 복사 문제
strncpy((*dst)->id,bufSection[0],strlen(bufSection[0])); strncpy((*dst)->action,bufSection[1],strlen(bufSection[1])); strncpy((*dst)->pipe_id,bufSection[2],strlen(bufSection[2]));요기서 strncpy호출하기전에
(*dst)->id ,action 등에 malloc을 먼저 하시던지
strdup함수를 사용하면 될것 같네요.
감사합니다! 바로 해결되었습니다
감사합니다! 바로 해결되었습니다
댓글 달기