0

当我在循环中调用 free 时,我在 C 中进行了一些文本提取并获得了一些“垃圾字符串”。这是一些示例文本:

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;
    }
4

1 回答 1

1

我怀疑您正在复制的字符串不是以 null 结尾的,并且在打印时可能包含垃圾字符。

来自man strncpy

strncpy() 函数类似,只是最多复制 n 个字节的 src。警告:如果 src 的前 n 个字节中没有 null 字节,则放在 dest 中的字符串不会以 null 结尾

于 2013-06-12T20:07:07.047 回答