Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can an array receive values more than it is declared to hold

int main(void)
{
    char name1[5];
    int count;
    printf("Please enter names\n");
    count = scanf("%s",name1);
    printf("You entered name1 %s\n",name1);
    return 0;
}

When I entered more than 5 characters, it printed the characters as I entered, it was more than 5, but the char array is declared as:

char name1[5];

Why did this happened

like image 760
user2556058 Avatar asked Nov 29 '22 08:11

user2556058


1 Answers

Because the characters are stored on the addresses after the 'storage space'. This is very dangerous and can lead to crashes.

E.g. suppose you enter name: Michael and the name1 variable starts at 0x1000.

name1: M       i     c      h      a      e      l     \0
      0x1000 0x1001 0x1002 0x1003 0x1004 0x1005 0x1006 0x1007
      [................................]

The allocated space is shown with [...] This means from 0x1005 memory is overwritten.

Solution:

Copy only 5 characters (including the \0 at the end) or check the length of the entered string before you copy it.

like image 170
Michel Keijzers Avatar answered Dec 15 '22 06:12

Michel Keijzers