-3

I am pretty new to C and I have tried the following code

#include <stdio.h>

int main ()
{
  char str[] = "a";
  for(int x = 0; x < 20; x++)
  {
    printf("%c\t%d\n", str[x],str[x]);
  }
  return 0;
}

For which I get the following output

a   97
    0
    0
s   115
<   60
�   -62
)   41
P   80
�   -42
�   -128
0   48
�   -41
>   62
�   -119
�   -88
U   85
    0
    0
�   -105
�   -85

After str[2] the chars are random for each execution, can someone please explain this behavior.

Zi Fit
  • 11
  • 5

2 Answers2

1

These random characters are just garbage from the memory. You read from a place in the memory you have not written intentionally.

Note that one should not do it. If you try to read from/write to memory you are not suppose to read from/write to, OS might kill your application.

asikorski
  • 882
  • 6
  • 20
0

After str[2] the chars are random for each execution, can someone please explain this behavior.

The behavior can't be explained; it's undefined to read or write beyond the bounds of the array. Since you have allocated two chars for str (one for the letter "a", and the other for the null terminator), reading beyond str[2] invokes undefined behavior, meaning that anything could happen, including breathing demons out of your nose.

lost_in_the_source
  • 10,998
  • 9
  • 46
  • 75