1

Following is the code :

#include<stdio.h>
int main(){

    char a[6]; // DECLARATION OF ARRAY OF CHARACTER WITH SIZE 6
    printf("Enter ur Name :");
    scanf("%s",a); // INITILISATION OF ARRAY

    printf("\nName : %s\n",a); //PRITNTING WHAT GETS STORED IN A 

    for (int i = 0; i < 10; ++i)
    {
        printf("%c .",a[i]); // PRINTNING A WITHIN BOUND 10.
    }
    return 0;
}

I am getting following output :

Enter ur Name :DESKTOP                      

Name : DESKTOP                    **//Why DESKTOP is being printed ? shouldn't be DESKTO**
D .E .S .K .T .O . . . . .                                                   

Why i am getting DESKTOP .. as a size is 6 hence a must have stored DESKTO .

  • 1
    Accessing out of bounds elements is Undefined Behaviour. C will let you do it but the result is undefined - it could crash, could give wrong values, could even appear to "work". – kaylum Jun 15 '21 at 05:24

1 Answers1

1

The function scanf() is not for the faint of heart to use. Studying the documentation is important; e.g. https://en.cppreference.com/w/c/io/fscanf .

If you expect it to only read at most a certain number of letters, which is wise for the obvious reasons you just found out (i.e. UB, buffer overflow vulnerabilities, the works, see the comment and link by kaylum), then you need to tell it explicitly to do so.

You can do so like this

scanf("%5s",a); /* five because of the unconditional terminator... */

To read only to the allowed size, 5 +1 terminator.

This is necessary, because the simple scanf("%s",a); means "Read recklessly until you find a terminator; never mind the size of the receiving memory/array."

Changed as proposed, your code gets the desired output (one fewer, otherwise increase array size and use 6):

Enter ur Name :
Name : DESKT
D .E .S .K .T . . . . . .

It still has weird output from beyond the array (still bad UB) but that is because of your output with 10, i.e. too long.

If you also change to

char a[10]={'0','1','2','3','4','5','6','7','8','9'};

you get the englightening output

Enter ur Name :
Name : DESKT
D .E .S .K .T . .6 .7 .8 .9 .

Note the invisible terminator at index 5.

Or with scanf("%6s",a); (which is OK for the now bigger array):

Enter ur Name :
Name : DESKTO
D .E .S .K .T .O . .7 .8 .9 .

i.e. what you were expecting.

Yunnosch
  • 26,130
  • 9
  • 42
  • 54