What happens when assign a value to an a开发者_JAVA百科rray if the subscript exceeds the size of the array in C?
In other languages it throws an exception, does C also throw an exception? For some reason i dont get any errors
What happens when assign a value to an array if the subscript exceeds the size of the array in C?
Bad thing happens. Or not. In fact, the standard states it's undefined behavior which means anything can happen.
In other languages it throws an exception, does C also throw an exception?
No.
It highly depends on the program, the compiler and system. Windows usually is more strict with out of bounds memory, while Linux can give you some extra space, which can make the program to work correctly (even there's a problem).
If you're lucky, the system will crash immediately and you'll notice the error the moment it appears. If you're not lucky, that will change a completely unexpected (but correct from the point of view of the program) variable and will create strange bugs on completely different parts of the code from the one that causes the issue. These are probably the worst bugs on C...
In Linux systems, a great tool is Valgrind, which will check this kind of problems (among others). Unfortunatelly, I don't know a equivalent tool on Windows... :-(
C is not able to throw exceptions, so...
It is undefined. Which means you may end up overwriting another variable of if you are unlucky do absolutely nothing.
This question has some good answers that may be worth a look at.
C also don't have exceptions, which means it can't throw them.
Writing past the end of an array means that you are writing into another bit of memory. What happens depends on what the computer is doing with that memory at the time.
If the memory is owned by another program, you will probably get an exception or crash the program.
If you own the memory, you change that value. Maybe it is a loop counter and you'll get an infinite loop. Maybe it is the address on the hard disk that you are about to write and you will trash the file system. Maybe it is being ignored and nothing will happen.
So the answer to "what will happen?" is "pretty much anything, including 'nothing'".
In modern programming there is just no excuse for buffer overruns. Don't do it.
The behavior is undefined; anything (for reasonable values of "anything") can happen. Your program may appear to work correctly, you may corrupt some memory that causes problems later in the program execution, you may trigger a segmentation violation, or something else may happen. Buffer overruns are a common exploit for malware.
精彩评论