-1

I wrote a program to try and print a 2D table containing a graphical representation of user input using a 2D array in C. I compile and run this program, but not matter how much I press Return or Ctrl+D for EOF, getchar does not appear to yeilding to the instructions in the loop as expected. What am I doing wrong here?

int main()
{
    /*ignore these comments, they are outdated todo lists*/
    /* make vars init here, change for to while */
    /* finish printing */
    int c;
    int i, sec, other;
    char ndigit[3][8];

    while((c = getchar()) != EOF) {
        if (c == '\n' || '\t' || ' ') {
            for(i = 0; i < 63; ndigit[1][i] += 1);
                ;
        }
        else if (c >= '0' || c <= '9') {
            for(sec = 0; sec < 63; ndigit[2][sec] += 1)
                ;
        }
        else
            for(other = 0; other < 63; ndigit[3][other] += 1)
                ;
    }
    for (i = 0; i <= 3; ++i)
        for (sec = 0; sec <= 8; sec++)
            printf("%s\n", ndigit[i][sec]);
}
John Doe
  • 1
  • 1

1 Answers1

1

Compile with all warnings & debug info (gcc -Wall -Wextra -g, notably on Linux, which I recommend for beginners and experts). You'll probably get many useful warnings from your compiler (if possible use a recent version of GCC, since GCC is improving its diagnostics over time....). Improve your code till you get no warnings at all. Then use a debugger (gdb), notably to run your program step by step. Perhaps add some debug prints. You might be interested in also using valgrind and the address sanitizer.

Notice that in:

 for(other = 0; other < 63; ndigit[3][other] += 1);

other is not changing (you might forgot an other++, and then you'll get a buffer overflow if you add it, because ndigit[i][j] makes sense only for 0 <= i < 3 and 0 <= j < 8); so you have an infinite loop.

A buffer overflow is one way to have undefined behavior (UB). You should be very scared of UB and work very hard to avoid UB. Here I explain why.

Community
  • 1
  • 1
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
  • You were right, I did forget to increment the variables, and I did in fact get a segfault after adding the increment to the loop. However, I am confused as to why I got a segfault when I had other < 63 in the for loop's conditions. How is this possible? – John Doe Sep 11 '15 at 06:49