问题描述:

This question already has an answer here:

  • why doesn't my program crash when I write past the end of an array?

    8 answers

  • How dangerous is it to access an array out of bounds?

    10 answers

网友答案:

I mean I can legally assign the string of length 5 to a string declared with size 1.

No, you can't. You've written past the end of the buffer, which invokes undefined behavior. The code is erroneous, but the language standard places no requirements on the compiler to handle the situation in any particular way. The result can be anything from an immediate crash to garbled output to working exactly as expected. It all depends on what follows s in memory.

C does no bounds checking on array accesses; the language assumes you're smart enough not to access elements outside of the array bounds. It won't throw an exception if you read or write past the end of the array. As long as you don't clobber anything important, your code will appear to function normally.

相关阅读:
Top