2014-12-03 9 views
0

char로 파일 char를 읽습니다. 콜론에 도달하면 개행 문자에 도달 할 때까지 모든 문자를 건너 뛰고 싶습니다. 사실, 콜론을보고 나면 다음 라인으로 건너 뛰고 싶습니다 (다른 라인이있는 경우). 충분히 단순 해 보이지만 걱정하지 않는 데이터를 건너 뛰는 두 번째 while 루프에서 벗어날 때 sigsegv를 수신합니다.C fgetc sigsegv - 행 끝으로 건너 뛰기

중단없이 코드는 예상대로 작동합니다 (원하는 출력은 아님). 즉, 첫 번째 콜론까지 데이터를 읽은 다음 EOF로 건너 뛰고 종료합니다.

 5 FILE *fp = fopen("myFile", "r"); 
     6 char *string = (char*) malloc(sizeof(char)); 
     7 char *head = string; 
     8 if(fp){ 
     9  int c; 
    10  while((c=fgetc(fp)) != EOF){ 
    11   if(c == ':'){ 
    12    *string++ = '\n'; 
    13    while((c=fgetc(fp)) != EOF){ 
    14    if(c == '\n')    // Skip to end of line 
    15     break; //removing break avoids sigsegv 
    16    } 
    17   }else{ 
    18    *string++ = c; 
    19   } 
    20  } 
    21 } 

내가 루프의 탈옥 할 때, 하나 c 또는 fp가 SIGSEGV 원인이 어떻게 든 수정 될 것으로 보인다. 내 생각 엔 fp이 어떻게 든 수정되어 부모 fgetc()fp을 호출하면이 오류가 발생합니다. 그 외에도, 나는 그 문제를 일으키는 것이 확실하지 않습니다.

+0

http://stackoverflow.com/help/mcve –

+0

GDB (또는 유사한 디버거)를 사용하여 크게 문제의 근본 원인을 발견하는 데 도움 것입니다. – user3629249

답변

2

string에 대해 더 많은 바이트를 할당해야합니다. 이 줄은

char *string = (char*) malloc(sizeof(char)); 

입니다. 문자열은 1 바이트 만 할당합니다.

+0

중단을 제거해도 오류가 발생하지 않는 이유를 설명 할 수 있습니까? 더 많은 메모리를 할당하지 않아도 많은 문자를 인쇄 할 수 있습니다. 솔직하게 나에게 이상하게 보였다. –

0
the main problem was writing to offset from a pointer 
that did not point anywhere in particular 
which is a major reason for getting seg fault events 
note: 'string' is a well known C++ class name 
     so changed the name to pBuffer 
The following code snippet fixes that problem (and a few others) 


    int memorySize = 1024; 
    char *realloc_result = NULL; 
    char *pBuffer = malloc(memorySize); 
    if(NULL == pBuffer) 
    { // then, malloc failed 
     perror("malloc failed"); 
     exit(EXIT_FAILURE); 
    } 

    // implied else, malloc successful 

    FILE *fp = fopen("myFile", "r"); 
    if(NULL == fp) 
    { // then fopen failed 
     perror("fopen failed for read"); 
     fclose(fp); 
     exit(EXIT_FAILURE); 
    } 

    // implied else, fopen successful 


    int c;  // input buffer char 
    int i = 0; // loop counter 
    while(EOF != (c=fgetc(fp))) 
    { 
     if(i >= memorySize) 
     { // then need more memory 

      if(NULL == (realloc_result = realloc(pBuffer, memorySize*2)) 
      { // then realloc failed 

       perror("realloc failed"); 
       free(pBuffer); 
       fclose(fp); 
       exit(EXIT_FAILURE); 
      } 

      // implied else, realloc successful 

      memorySize *= 2; // track current amount of allocated memory 
      pBuffer = realloc_result; // update ptr to allocated memory 
     } // end if 

     if(':' == c) 
     { // then, terminate buffered line and skip to end of input line 

      pBuffer[i] = '\n'; 
      i++; 

      // skip to end of line 
      while(EOF != (c=fgetc(fp))) 
      { 
       if('\n' == c) 
       { // then, reached end of input line 
        break; // exit inner while 
       } // endif 
      } // end while 

      if(EOF == c) 
      { // then, at end of file 
       break; // exit outer while 
      } // end if 
     } 

     else 
     { // not skipping data 
      pBuffer[i] = c; 
      i++; 
     } // end if 
    } // end while