0

I am working on a HW assignment dealing with a dynamically allocated array that can handle different sized input files. My issue is that a pair of (null) values keep appearing tied to the word_alloc variable (changing it moves where in the output the (null) appears). How do I fix this?

int main(int argc, char *argv[]) {
    char str[80];
    int word_alloc = 0;
    int word_count = 0;
    char **str_array;

    FILE *file;
    file = fopen("hw3-data.txt", "r");

    // Allocate memory to the array of strings (char arrays)
    word_alloc = 10;
    str_array = (char **) malloc(sizeof(char*) * word_alloc);

    while (fscanf(file, "%s", str) != EOF) { 
        //doubles the word_alloc/str_array if we have more words than allocated
        if(word_count > word_alloc) {
            word_alloc *= 2;
            str_array =(char **) realloc(str_array, sizeof(char*) * word_alloc);
        }

        str_array[word_count] = (char *) malloc(sizeof(char) * (strlen(str) + 1));
        strcpy(str_array[word_count], str);
        ++word_count;
    }

    return 0;
}

here is the output

0

1 Answer 1

1

The errors happen because you have array overflow. Change

if(word_count > word_alloc)

to

if(word_count >= word_alloc)

to fix it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.