简体   繁体   中英

C free garbages char pointer

I doing some text-extraction in C and getting some 'garbage-strings' when i call free on my loop. Here is some sample text:

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]

Question:

1 - Can i safely reuse the pointer variable after free it?

Thanks for any help!

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

I suspect that the string you are copying are not null terminated and when printed might include garbage chars.

from man strncpy :

The strncpy() function is similar, except that at most n bytes of src are copied. Warning: If there is no null byte among the first n bytes of src, the string placed in dest will not be null-terminated .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM