0

What's stored after the end of character array? I was assuming there would be some random garbage but it did not print anything after the end while looping 10 times.

char a[] = "Pencil";
int i;

for (i = 0; i < 10; i++)
{
    printf("%c", a[i]);
}

so the character array a has the size of 7. And for loop looped until 10th position which are 3 more values looped through. But it did not print anything or Error. What's going on here?

Jin kim
  • 155
  • 1
  • 2
  • 8
  • 6
    Undefined behavior is exactly that, undefined. Anything can happen, including *seemingly* sane behavior. – R Sahu Jul 11 '15 at 04:55
  • If you run the output through a hex dump program, you're likely to find that there were three characters printed after the terminal null, but that's not guaranteed and their values are not guaranteed either. They might have been null bytes; they might have been control characters. – Jonathan Leffler Jul 11 '15 at 04:56
  • The three characters in the locations beyond the end of your string may not be printable. –  Jul 11 '15 at 04:57
  • Accept one of life's great mysteries. ;) – Pynchia Jul 11 '15 at 06:16

2 Answers2

1

Accessing beyond the end of an array in C is undefined behavior. Your program could continue running unchanged or it could crash horrifically depending on what is stored past the end of the array. The compiler makes no guarantees about what is stored there - it could be useless memory or it could be critical to your program.

Erik Godard
  • 5,930
  • 6
  • 30
  • 33
0

Accessing an array element beyond the array-length invokes undefined behavior which means anything could happen.

ameyCU
  • 16,489
  • 2
  • 26
  • 41