Java Reference
In-Depth Information
Thus
address ( struct [ i ]
. field )
= address ( struct [ i ])
+ o ff set ( field )
= address ( struct )
+ i size ( struct )
+ o ff set ( field )
For example,
address ( ar [5]
. b )
= address ( ar [5])
+ o ff set ( b )
= address ( ar )
+
40
+
4
= address ( ar )
+
44
In Java and C
, arrays are allocated as objects; all the elements of the array are
allocatedwithin the object. Exactly how the objects are allocated is unspecified
by Java's definition, but a sequential contiguous allocation, just like CandC
++
,
is the most natural and e
cient implementation.
Array Bounds Checking
An array reference is legal only if the index used is in bounds. References
outside the bounds of an array are undefined and dangerous, as data unrelated
to the array may be read or written. Java, with its attention to security, checks
that an array index is in range when an array load or array store instruction is
executed. An illegal index forces an ArrayIndexOutOfBoundsException.Since
the size of an array object is stored within the object, checking the validity of
an index is easy, though it does slow access to arrays.
In C and C
array indices out of bounds are also illegal. Most compil-
ers do not implement bounds checking, and hence program errors involving
access beyond array bounds are common.
Why is bounds checking so often ignored? Certainly speed is an issue.
Checking an index involves two checks (lower and upper bounds) and each
check involves several instructions (to load a bound, compare it with the index,
and conditionally branch to an error routine). Using unsigned arithmetic,
bounds checking can be reduced to a single comparison (since a negative
index, considered unsigned, looks like a very large positive value). Using the
techniques of Chapter 14, redundant bounds checks can often be optimized
away. Still, array indexing is a very common operation, and bounds checking
adds a real cost (though buggy programs are costly too!).
A less obvious impediment to bounds checking in C and C
++
is the fact
that array names are often treated as equivalent to a pointer to the array's first
element. That is, an int[]and a *intare often considered synonymous. When
an array pointer is used to index an array, we do not know what the upper
bound of the array is. Moreover, many C and C
++
programs intentionally
violate array bounds rules, initializing a pointer one position before the start
++
 
Search WWH ::




Custom Search