开发者

Why this bizarre output in c?

开发者 https://www.devze.com 2023-04-05 20:33 出处:网络
I have the following program #include <stdio.h> main() { char ch[10]; gets(ch); printf(\"\\nTyped: %s\\n\\n\", ch);

I have the following program

#include <stdio.h>

main()
{

    char ch[10];

    gets(ch);

    printf("\nTyped: %s\n\n", ch);

    int i = 0;
    while ( ch[i] != '\0' )
    {
        printf("Letter: %c\n", ch[i]);
        i++;
    }

    printf("\nTyped: %s\n\n", ch);


}

and here is the output when i typed "Hello world is good"

hello world is good

Typed: hello world is good

Letter: h
Letter: e
Letter: l
Letter: l
Letter: o
Letter:
Letter: w
Letter: o
Letter: r
Letter: l
Letter:


T开发者_开发技巧yped: hello worl♂

Why i am getting two different output for same command after while loop? does while loop has anything to do with it.. please help..


You do know that "Hello world is good" is more than 10 bytes? The behavior in this case is undefined. Anything can happen, anything at all, from working as you wanted to total crash of your system with reformatting the hard-drive and burning junk over your ROM.

You must allocate enough space for gets to put the string in, and in this case you don't. That's the main reason why gets should be avoided, use fgets instead.


Your character array ch only has space for 10 chars. You typed something longer than 10 chars and tried to store it in that array, effectively writing beyond the end of the array into space that's not reserved for anything (or at least isn't reserved for your characters). You got lucky in this case and didn't write over anything important (your program didn't crash), but subsequent code comes along (the printf(), your int i, etc.) and changes that memory (it's the stack, after all, so it gets used in FIFO order).

Change your char ch[10] to char ch[2048] to give yourself a larger buffer to type into. You might also use fgets() instead of gets() so that you can limit the size of the input to your buffer size. If you use gets(), heed the warning on the man page:

It is the caller's responsibility to ensure that the input line, if any, is sufficiently short to fit in the string.


Well, you allocate only 10 characters (char ch[10]) which fits "hello worl". Afterwards there's only junk in memory you're trying to print.

0

精彩评论

暂无评论...
验证码 换一张
取 消