I didn’t even analyze the code to see the exact problem, but what people need to keep in mind is that C is a permissive language, it lets almost everything happen, and it’s the programmer’s problem to take care not to give trouble. Some compilers even have options to better handle certain situations, libraries help a little not happen terrible things when you use their functions, have external tools, but the programmer must know what you are doing and be in control of everything. This is the biggest advantage of C, so it is fast and flexible, but charges the price.
In a way it’s good because it creates serious problems and it makes people who don’t get along with programming so much that they get away from it as it makes them realize that not everything that works is right. When the person understands this and puts a strong focus on his work always considering it he ends up turning professional with capital P.
Languages that are permissive in things that do not cause such serious problems addict the "programmer" in making it work, even if it is wrong.
C has no robust memory controls, you allocate a buffer and it’s your problem to manage it. If you screw up your bad luck. And if nothing else causes trouble it looks right, and it works, it doesn’t make a mistake, but it either comes out unexpected or it’s all right by coincidence. In exercises it is very common to be right by coincidence after the code is so simple that it does not generate conflict, and it is exactly what happened in this code, it is so small that it did not even have opportunity to corrupt the memory, but start doing something else and it will happen.
Memory is there for you to use with freedom. Great powers, great responsibilities. You put it in an undeclared area, the compiler lets, if you don’t use the outdated area, ok, if you declare something else there and use it will get data loss.
Technically there was no memory invasion because C has all memories of the process at his disposal, conceptually yes, there was intrusion, and concepts fix us doing it the right way.
Each compiler can, depending on the machine architecture, leave some unallocated byte(s)/filled(s) to optimize the alignment of the allocated variables. The C language considers that the programmer knows what he is doing and does not suppress, for example, the overflow of memory. You may get lucky and the array overflows into these unused bytes, but it can bring bad luck and fall into a memory area used by another variable.
– anonimo
Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site (when you have enough score).
– Maniero