0

I made a code that inputs four letters, and prints an '*' in place of each one, as in a password. The working code is this:

#include <stdio.h>
#include <conio.h>
int main()
{
    int c = 0;
    char d[4];
    printf("Enter a character:");
    while (1)
    {
        if (_kbhit())
        {
            d[c] = _getch();
            printf("*");
            c++;
        }
        if (c == 4)
            break;
    }
    system("cls");
    for (c = 0; c <= 3; c++)
        printf("%c", d[c]);
}

Now I have two questions: 1) Why do I get four ╠'s when I change the loop to:

for (c = 0; c <= 4;c++)
    {
        if (_kbhit())
        {
            d[c] = _getch();
            printf("*");
        }
    }

and 2) Why do I get an extra ╠ at the end when I change the second loop's upper limit to c<=4?

The second loop being this:

for (c = 0; c <= 3; c++)
        printf("%c", d[c]);
  • When c is 4, you are reading/writing outside the bounds of the array, which in your case is on the stack, so you are corrupting what is after the array on the stack. – DBug Dec 18 '15 at 17:48
  • Well, `c[4]` would be reading outside the end of the array (index #5 of a length-4 array). The value you get there (which ends up printing as ╠) is a chunk of arbitrary memory that happens to contain that value (e.g. it could be a byte of the program code itself, but is likely another variable object). – Draco18s no longer trusts SE Dec 18 '15 at 17:50
  • ╠ is 0xCC in codepage 437, and [MSVC fills 0xCC to uninitialized memory to help debugging](https://stackoverflow.com/q/370195/995714). That means you've accessed uninitialized memory. You can find tons of questions about ╠ and 0xCC here on SO – phuclv Aug 18 '18 at 10:57

1 Answers1

0

Cause the for loop iterates 4 times no matter if _kbhit() returns true or false. The while loops until _kbhit() returns true 4 times

For the second question, d[4] is out of the bounds of the array, the same value is just coincidence

Mr. E
  • 2,070
  • 11
  • 23