C免费垃圾char指针

时间:2013-06-12 20:01:18

标签: c free scanf

我在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;
    }

1 个答案:

答案 0 :(得分:1)

我怀疑你复制的字符串不是空终止,打印时可能包含垃圾字符。

来自man strncpy

strncpy()函数类似,只是复制了最多n个字节的src。警告:如果src的前n个字节中没有空字节,则放置在dest 中的字符串将不会以空值终止