-3

I'm trying to understand why the following program acts in such a weird way. I declare an array of chars, and input chars into it, with a while loop and scanf. However when I input letters, or digits, it runs seemingly forever. If I input a large number, or a string, it stops. Why doesn't it exit the loop after 5 iterations?

// This program runs forever if we input single-digit numbers
#include <stdio.h>

int main() 
{
    char u[5] = {0,};
    for (int i = 0; i<5; i++) {
        scanf(" %s", &u[i]);
    }
    printf("%s\n", u);
}
blz
  • 403
  • 6
  • 12

1 Answers1

4

This is broken beyond repair.

scanf("%s", ...) is always a severe bug, because you can't know your input in advance, and %s matches any sequence of non-whitespace characters, of any length -- there's no way to know how large your buffer must be.

%s writes the characters it reads starting at the address you pass as argument. It writes an additional 0 byte as the end mark of a string. So with your code, even if you only enter single characters, the last iteration writes this 0 byte at u[5] which is out of bounds, you overflowed your buffer.

You can't even fix it by just changing %s to %c (which matches a single character) because you don't add a 0 byte to the end of your array, so the array content is not a string and passing it to printf("%s", ...) is again undefined behavior.

Start over, read a good book on C first, and when you're done, best forget about scanf() and use better methods for input like fgets(). See also How to read / parse input in C? The FAQ and my beginners' guide away from scanf().

  • But why doesn’t it break from the for loop after 5 iterations ? – blz Nov 02 '17 at 09:54
  • @blz because undefined behavior is undefined. Anything could happen when you e.g. overflow a buffer. –  Nov 02 '17 at 09:55