fgets에서 segmentation fault가 뜨는데 이유를 모르겠습니다.
글쓴이: yeonjooo / 작성시간: 일, 2015/09/20 - 5:14오후
#define BUF_SIZE 2500 #define ACTION_ONCE 1001 #define ACTION_WAIT 1002 #define ACTION_RESPAWN 1003 void check_cmd(char **); int main (int argc, char **argv){ if (argc <= 1) { fprintf (stderr, "configuration file must specified\n"); return -1; } char *fileName=argv[1]; char *str=(char*)malloc(sizeof(char)*BUF_SIZE); FILE *fp; if((fp=fopen(fileName,"r"))==NULL){ fprintf (stderr, "failed to load config file %s \n", fileName); return -1; } while(!feof(fp)){ fgets(str,BUF_SIZE,fp);//error가 나는 부분 check_cmd(&str); printf("%s\n",str); } free(str); fclose(fp); return 0; } void check_cmd(char **str){ if(*str[0]=='#'){ *str="# command"; } }
Forums:
check_cmd 에 if 조건이 참이 되어 블록
check_cmd 에 if 조건이 참이 되어 블록 안에 들어가면 main 함수의 str 변수는 더 이상 malloc 으로 할당받은 공간이 아니라 "# command" 문자열의 주소를 가리키게 되겠네요. 저 위치는 (거의 모든 경우) 읽기 전용으로 되어 있을 테고요. 그러면 그 다음 fgets 에서 그 공간에 값을 쓰려다가 죽습니다.
입력받은 str의 내용을 변경하고 싶은거면 strcpy 를 써서 덮어 쓰세요.
좋은 하루 되세요!
감사합니다~ 저 한줄때문에 몇시간을 고민했는데 ㅠㅠ
감사합니다~ 저 한줄때문에 몇시간을 고민했는데 ㅠㅠ 아직 멀었네요 더 많이 공부해야겠습니다
댓글 달기