OrangeBike
OrangeBike

Reputation: 145

why does this code give me runtime error? C

I don't understand why it keeps giving runtime errors :/ What is wrong in there? How can I resolve this problem? Here is my code:

#include <stdio.h>

int main() 
{
    int i=0, ch;
    char word[100];
    for(;(ch = getc(stdin)) != EOF;)
    {
        do{
            word[i] = ch;
            if(ch == 32) word[i] = '\0';
            i++;
        } while(ch != 32);

    }
    printf("%s", word);
    return 0;
}

Upvotes: 0

Views: 391

Answers (2)

dbush
dbush

Reputation: 225417

In this loop:

    do{
        word[i] = ch;
        if(ch == 32) word[i] = '\0';
        i++;
    } while(ch != 32);

The value of ch never changes, so you have an infinite loop. You also as a result end up writing past the end of the buffer word because i is increasing without bound, invoking undefined behavior.

You don't need two loops here. Just check for both EOF and a space. Also, you should use the character constant ' ' for a space instead of its ASCII code.

for (i=0; ((ch = getc(stdin)) != EOF) && (ch != ' '); i++)
{
    word[i] = ch;
    if(ch == ' ') word[i] = '\0';
}

Upvotes: 3

Blindy
Blindy

Reputation: 67487

    do{
        word[i] = ch;
        if(ch == 32) word[i] = '\0';
        i++;
    } while(ch != 32);

You're overflowing your buffer on the first key press. Which should point out the broader problem of a fixed size buffer with no range checking, in addition to this broken piece of code.

Upvotes: 3

Related Questions