2013-06-12 2 views
0

내 루프에서 을 무료로 호출 할 때 C에서 일부 텍스트 추출을 수행하고 '쓰레기 문자열'을 가져 오는 중입니다. 다음은 몇 가지 샘플 텍스트는 다음과 같습니다C 무료 garbages char 포인터

Sentence #1 (34 tokens): 
The Project Gutenberg EBook of Moby Dick; or The Whale, by Herman Melville 

This eBook is for the use of anyone anywhere at no cost and with 
almost no restrictions whatsoever. 
[Text=The CharacterOffsetBegin=0 CharacterOffsetEnd=3 PartOfSpeech=DT Lemma=the]      [Text=Project CharacterOffsetBegin=4 CharacterOffsetEnd=11 PartOfSpeech=NN Lemma=project] 

질문 :

1 - 내가 안전하게 확보 한 후 포인터 변수를 재사용 할 수 있습니까?

도움 주셔서 감사합니다.

#include <stdio.h> 
    #include <stdlib.h> 
    #include <string.h> 

    #define LINE_M (1024*100) 

    int main(int argc, char **argv) 
    { 

     FILE *file; 
     char buff[LINE_M]; 
     char *lemma; 
     char *text; 
     char *sentence = NULL; 
     char *p, *t; 
     int numSent, numTok; 

     file = fopen("moby.txt.out", "r"); 


     while (fgets(buff, LINE_M, file)) 
     { 
     if(sscanf(buff, "Sentence #%d (%d tokens):", &numSent, &numTok)) 
      continue; 

     if(strstr(buff, "[Text=") == NULL) 
     { 
      if(sentence != NULL) 
      { 
      sentence = realloc(sentence, (strlen(buff) + strlen(sentence) + 2) * sizeof(char)); 
      strcat(sentence, buff); 
      } 
      else 
      { 
      sentence = malloc(sizeof(char) * (strlen(buff) + 1)); 
      strcpy(sentence, buff); 
      } 

      continue; 
     } 
     p = buff; 
     while ((p = strstr(p, "Text=")) != NULL) 
     { 

      p += 5; 
      t = strchr(p, ' '); 

      text = malloc((int)(t - p)); 
      strncpy(text, p, (int)(t - p)); 

      p = strstr(t + 1, "Lemma=") + 6; 
      t = strchr(p, ']'); 

      lemma = malloc((int)(t - p) * sizeof(char)); 
      strncpy(lemma, p, (int)(t - p)); 

      p = t + 1; 

      printf("%s\n", lemma); 
      free(text); 
      free(lemma); 

      text = NULL; 
      lemma = NULL; 

     } 
     free(sentence); 
     sentence = NULL; 

     } 

     fclose(file); 

     return 0; 
    } 
+0

해제 된 포인터가 가리키는 메모리를 다시 사용하는 것은 좋지 않지만 해제 한 이전 메모리를 저장했던 동일한 슬롯에 새 포인터를 저장하는 것이 좋습니다. (당신이 물어 본 내용은 2 번째 경우입니다.) – DaoWen

답변

1

복사중인 문자열이 null로 끝나지 않았으며 인쇄 할 때 가비지 문자가 포함 된 것으로 의심됩니다. man strncpy에서

:

SRC 대부분 n 바이트가 복사에서의 strncpy() 함수는 것을 제외하고는 유사하다. 경고 : src의 처음 n 바이트 사이에 널 바이트가 없으면, 에 놓인 문자열은 널로 끝나지 않습니다.

+0

문자열은'NULL'은 종료되지 않지만 null은 종료되었습니다. –

+1

당신이 그 과격파가되기를 원하면 : 그들은 \ '종료됩니다. – Kninnug

+1

실제로 NUL이 가장 적절하다고 생각하지만 어쨌든 그것을 변경했습니다. 감사. – eyalm