This is happening due to what we call undefined behavior.
An undefined behavior (UB) is a result of executing computer code whose behavior is not prescribed by the language specification to which the code can adhere to, for the current state of the program (e.g. memory). This generally happens when the translator of the source code makes certain assumptions, but these assumptions are not satisfied during execution.
In simple word, there is no such restriction mentioned or specified in C’s language specification.
Languages like java have some functionality implemented that generates exception if someone access an array out of bound/defined range to prevent such access.
But, in case of C/C++ there is no such functionality preventing access. Thus, your code is returning a garbage value from an undefined memory location.
Hope, this would help.
Give a like, if you are satisfied.