-1

who can tell me why the code below still works? it is obvious that the str[4] is out of boundry:

#include<stdio.h>
int main(){
    char str[3];
    scanf("%s", str);
    printf("%c\n", str[4]);
    printf("%s\n", str);
    return 0;
}

when it runs, enter abcdefg, it will echo the 5th char and the whole string, nothing will be wrong, weird?

It has been declared that c/c++ doesn't do the boundary checking, while in the case above, how should I use printf to print a c-string that the user has entered? or more generally, how to properly use a c-string that comes from users?

comeonfox
  • 55
  • 1
  • 6

3 Answers3

2

str[4] gives you a pointer to the memory address after the last element of your string. You can still convert this to a character, but you never know what you get and your software might crash.

Coert Metz
  • 894
  • 6
  • 21
  • Yes, it has been declared that c/c++ doesn't do the boundary checking, while in the case above, how should I use printf to print a c-string that the user has entered? or more generally, how to properly use a c-string that comes from users? – comeonfox Mar 03 '13 at 02:20
  • I think scanf is in general kind of dangerous as it does not prevent buffer overflows as you illustrate in your example. See also http://stackoverflow.com/questions/2430303/disadvantages-of-scanf for a discussion about this topic. – Coert Metz Mar 03 '13 at 10:38
1

Why does it work?

It doesn't "work". It might appear to be working, though; since your code (accessing an array out of bounds) invokes undefined behavior, you can get literally any result. Undefined behavior doesn't mean "it must crash".

0

You wrote:

when it runs, enter [abcdefg], it will echo the 5th char and the whole string, nothing will be wrong, weird?

but I see no input reading in the code you posted:

#include<stdio.h>
int main(){
    char str[3];
    printf("%c\n", str[4]);
    printf("%s\n", str);
    return 0;
}

In any case, str[4] points to the 5-th char (byte) starting from str, so it will print any "garbage" that happens to be in that memory location when your program runs.

Accessing array items out of bounds is undefined behavior, so the exact behavior is not specified. Just pay attention to your array bounds.

Mr.C64
  • 41,637
  • 14
  • 86
  • 162
  • Oh, I removed that line by mistake, it's been added now. another question: how should I properly use( like `printf("%s",str)`) a c-string that comes from user? – comeonfox Mar 03 '13 at 02:24