-1

Why I input 21 elements and it works fine? and If I input 22 it appears segmentation fault/stack smashing.(OS Linux). If I allocated only 20 elements. I've tried some sort of online compilers and there I could even write more elements.

My logic is that if we have 20 elements then we have elements of array from index 0 till index 19, and 20 index was written by machine with '\0' automatically.

Could you please explain to me how it works. Why It allows to write where you are not allocated to. And why stack smashing/segmentation fault appears on 22 elements rather than 21 elements.

Or could you please let me know what books do I have to use to find information about.

There is a piece of code below.

int n, i;
int a[20];

printf("Enter no of emelents of array\n");
scanf("%d", &n);
printf("\nEnter %d elements: ", n);
for(i = 1; i <= n; i++)
{
    scanf("%d", &a[i]);
}
salt en
  • 1
  • 1
  • 5
    UB͏͏͏͏͏͏͏͏͏͏͏͏͏ – Bathsheba Apr 18 '18 at 13:23
  • 3
    Array indices in C or C++ (You should choose one) begin at 0, not 1. – Retired Ninja Apr 18 '18 at 13:24
  • 2
    @Bathsheba how were you able to add a comment with less than 15 characters? o.O – tkausl Apr 18 '18 at 13:24
  • Accessing an array out of bounds is _undefined behaviour_ (google that term). – Jabberwocky Apr 18 '18 at 13:25
  • " Why It allows to write where you are not allocated to." because it is not obligated to validate your access. – Slava Apr 18 '18 at 13:28
  • @tkausl: You have to be very rich. – Bathsheba Apr 18 '18 at 13:32
  • *"My logic is that if we have 20 elements then we have elements of array from index 0 till index 19, and 20 index was written by machine with '\0' automatically."* The compiler adds the NULL terminator (and reserve enough space in memory for it) only when you initialize a **char** array with a string literal: `char str[] = "Hello";` --> `{'H', 'e', 'l', 'l', 'o', '\0'}`, because the string literal itself is null-terminated, but you have arrays of `int`s – Bob__ Apr 18 '18 at 13:41

1 Answers1

1

Notice you are writing from index 1 up to and including n. So if you input X (let's say, 20), your last element will be written to the X+1th index of your array.

That being said, accessing indexes out of your array boundaries renders undefined behavior (as already mentioned by @Bathsheba).

The reason a segmentation fault does not occur when accessing the 21th index, in your case, is probably that since your array was allocated in the stack, is is accessing allocated memory (which could be n, i, or even the program or stack counter).

This has already been asked in other questions, such as this one.

Guilherme Simas
  • 111
  • 1
  • 3