내 루프에서 을 무료로 호출 할 때 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;
}
해제 된 포인터가 가리키는 메모리를 다시 사용하는 것은 좋지 않지만 해제 한 이전 메모리를 저장했던 동일한 슬롯에 새 포인터를 저장하는 것이 좋습니다. (당신이 물어 본 내용은 2 번째 경우입니다.) – DaoWen