2014-01-21 4 views
0

C 프로그램에서 세그멘테이션 오류가 발생했으며 그 이유를 알 수 없습니다. 그것은 "디버그 6"후 인쇄 및 "세그먼트 화 오류 (11)."내 str_split_2 기능 때문에 직감이 있습니다.이 프로그램은 파일을 읽어야하는데, 첫 번째 줄은 n, 다음 두 줄 n 값 "A, B는". 나는 2 차원 배열지도에 그 값을 저장하고 싶습니다.세그먼트 오류 (11)

char** str_split_2(char* str, const char delim) 
{ 
    char** result; 
    result=(char**)malloc(2*sizeof(char*)); 
    result[0] = strtok(str, &delim); 
    result[1] = strtok(NULL, &delim); 
    return result; 
} 


int loadFile(int*** map, char* filename,int *n) 
{ 
    int i=0; 
    char *line = NULL; 
    size_t len; 
    FILE *fptr = fopen(filename, "r"); 
    if(fptr == NULL) 
    { 
     fprintf(stderr, "Error opening a file: %s\n", filename); 
     return 1; 
    } 

    getline(&line, &len, fptr); 
    *n = atoi(line); 
    printf("n: %d\n",*n); 
    *map = (int**) malloc((*n)*sizeof(int*)); 
    if(*map==NULL) 
     return 1; 
    char** sPosition=NULL; 
    printf("debug 0\n"); 
    for(i=0; i<*n; i++) 
    { 
     *map[i]=(int*) malloc(2*sizeof(int)); 
     printf("debut 1\n"); 
     if(*map[i]==NULL) 
      return 1; 
     printf("debug 2\n"); 
     getline(&line, &len, fptr); 
     sPosition=str_split_2(line,','); 
     printf("debug 3\n"); 
     printf("%s\n%s\n",sPosition[0],sPosition[1]); 
     printf("debug 4\n"); 
     *map[i][0]=atoi(sPosition[0]); 
     printf("debug 5 %d\n",*map[i][0]); 
     *map[i][1]=atoi(sPosition[1]); 
     printf("debug 6 %d\n",*map[i][1]); 
     printf("hello"); 
     printf("%d:",i); 
    } 

fclose(fptr); 
free(line); 
return 0; 
} 

답변

2

내가

*map[i]=(int*) malloc(2*sizeof(int)); 

(*map)[i]=(int*) malloc(2*sizeof(int)); 
map[0][i]=(int*) malloc(2*sizeof(int)); 

ELS 중 하나가 될해야한다고 생각 즉,

*(map[i])=(int*) malloc(2*sizeof(int)); 

이 잘못된 것 같습니다. 물론, 같은 문제는 널 종료 문자열 (즉, 문자열이 0 문자로 끝나야합니다)에 대한 포인터해야 strtok에 전달

*map[i][0]=atoi(sPosition[0]); 
    printf("debug 5 %d\n",*map[i][0]); 
    *map[i][1]=atoi(sPosition[1]); 
    printf("debug 6 %d\n",*map[i][1]); 
+0

감사합니다. 컴파일러에게 분명해야한다고 생각하지 않는 오류 유형입니다. – Xyzk

0

두 번째 인수에 있습니다.

문자 변수 (char delim)에 포인터를 전달하고 strtok "0"값이 나올 때까지이 주소에서 메모리를 "스캔"하므로 어떤 시점에서 잘못된 메모리 액세스를 수행 할 가능성이 큽니다.

BTW이 모든 str 루틴의 경우와 같은 strcpy, strlen, strcmp이다.