-3

How dangerous is it to access an array out of bounds? This does not tell what is the value stored.

When i try to print the out of array size elements as shown in the program, It is printing 0. Will it be always 0 or some garbage values.

Program

#include<stdio.h>
int main()
{
    int a[5] = {10};
    printf("\n\ra[6] = %d",a[6]);
    printf("\n\ra[7] = %d",a[7]);
    printf("\n\ra[8] = %d",a[8]);
    printf("\n\ra[9] = %d",a[9]);
    return 0;
}

Output

a[6] = 0 a[7] = 0 a[8] = 0 a[9] = 0

My question is what will be value of out of array size elements? Is it always garbage value or zero?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Embedded C
  • 1,448
  • 3
  • 16
  • 29
  • 1
    It's *undefined*, anything can happen with your invalid accesses. –  Jun 06 '17 at 11:15
  • @Stargateur nope it is different i am asking what will be the value – Embedded C Jun 06 '17 at 11:15
  • 2
    you know what *undefined* means? –  Jun 06 '17 at 11:16
  • 1
    @EmbeddedC This is really close, please read the answer of thread you will find what you ask. – Stargateur Jun 06 '17 at 11:17
  • as given in the program it will not give any error and it will give some value. My question is it is always garbage value or zero because in some compiler i am getting zero – Embedded C Jun 06 '17 at 11:21
  • Again, then, you know what undefined means? Felix has already asked once. Sourav has explained the UB further in his answer. It's UNDEFINED! What more could you possibly want? If you want/need to know what exactly is happening on your systen, feel free to run it under your debugger and find out. – ThingyWotsit Jun 06 '17 at 11:33
  • 1
    "*[Will] it always [print] garbage value or zero?*" - No, it could terminate your program, make demons fly out of your nose, and kill your firstborn. Undefined Behaviour is **undefined**. – Toby Speight Jun 06 '17 at 12:16

1 Answers1

4

When i try to print the out of array size elements....

Wait, stop!! Anything over a value of 4 for value of i (index) [C arrays use 0-based indexing] in case of an array defined like int a[5] = {10}; is invalid memory access which leads to undefined behavior. You cannot expect anything, at all.

  • If you're lucky, you'll probably receive a segmentation fault while running the program which strongly indicates some sort of invalid memory access.

  • If you're unlucky, the program might read the credit card number stored on your laptop and order pizza any pony for your team and transfer rest of the money to some anonymous account for ISIS. Iff you're willing to face that only then access out of bound memory, otherwise, refrain from doing it.

Summary: Just don't write code because you can, or the syntax is allowed. Try to make sense of the code to write. The array size is mentioned for a reson. If we did not have to regard the size, why's that size there, in fort place?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261