0

Reading in a string from a file and read in a sentence in order to find the number of sentences and words. When running this error is produced after reading in exactly 24 characters each time. I believe there is a problem with my realloc statement, however, I have no clue how to fix this. Here is the function:

void getSentence(FILE *fp, int *sentences, char *sentence)
{
    char currentLet;
    int length = 0;

    while ((currentLet = (char)fgetc(fp)) != '.' && currentLet != ':' && currentLet != ';' && currentLet != '?' && currentLet != '!')
    {
        printf("Current Sentence:%d %s\n", length, sentence);
        realloc(sentence, sizeof(char)*(length + 2));
        sentence[length] = currentLet;
        sentence[length+1] = '\0';
        length++;

    }

    return;
}

It will keep reading until it reaches the end of the sentence, as marked by the punctuation in my while loop condition.

I am compiling with these flags: gcc fleschIndex.c -Wall -std=c99 -o run

Edit: Thank you I changed the line to:

sentence = realloc(sentence, sizeof(char)*(length + 2));

Now I no longer have this error, but it still stops reading at exactly 39 characters.

  • 1
    `realloc` returns a pointer. It doesn't change the pointer that you passed to it. – user3386109 Feb 08 '19 at 02:45
  • here's my answer to an old question about correctly using realloc: https://stackoverflow.com/a/44789446/1212725. There are many other good ones – bruceg Feb 08 '19 at 02:49

0 Answers0