I have this code in C which takes in bunch of char
s
#include<stdio.h> # define NEWLINE '\n' int main() { char c; char str[6]; int i = 0; while( ((c = getchar()) != NEWLINE)) { str[i] = c; ++i; printf("%d\n", i); } return 0; }
Input is: testtesttest
Output: 1 2 3 4 5 6 7 8 117 118 119 120
My questions are:
Why don't I get an out of bounds (segmentation fault) exception although I clearly exceed the capacity of the array?
Why do the numbers in the output suddenly jump to very big numbers?
I tried this in C++ and got the same behavior. Could anyone please explain what is the reason for this?
The array index out of bounds error is a special case of the buffer overflow error. It occurs when the index used to address array items exceeds the allowed value. It's the area outside the array bounds which is being addressed, that's why this situation is considered a case of undefined behavior.
The StringIndexOutOfBoundsException is an unchecked exception in Java that occurs when an attempt is made to access the character of a string at an index which is either negative or greater than the length of the string.
The ArrayIndexOutOfBoundsException is a runtime exception in Java that occurs when an array is accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.
Note that C and C++ do not do bounds checking on arrays, so stuff like that isn't going to be caught at compile or run time. No, Undefined behavior "works in your favor" when it crashes cleanly.
str[i] = c
writes overwrites the value in i
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With