Discussion:
[Help-bash] Bash is corresponding weird towards invalid array index--Gao 2017.6.2
Zhiyuan Gao
2017-06-02 12:15:15 UTC
Permalink
Hi there!

When I was playing around with ubuntu 16.04.I tried
$array_1[0]=123
$array_1[1]=456
$array_1[2]=789

And it worked out fine with
$echo ${array_1[0]}
$echo ${array_1[1]}
$echo ${array_1[2]}

What is weird is when I type

$echo
${array_1[99999999999999999999999999999999999999999999999999999999999999999999]}

It actually returned 789!

And the fact is, script with 9s more than
$echo
${array_1[999999999999999999999999999999999999999999999999999999999999999]}
would be returning 789.
Those who end with 8 would be returning 456.
Those who end with 7 would be returning 123.

Is it a bug?

I thought it should be returning bad array script.

Thank you.

Gao Zhiyuan
2017.6.2
Greg Wooledge
2017-06-02 13:49:09 UTC
Permalink
Post by Zhiyuan Gao
$array_1[0]=123
$array_1[1]=456
$array_1[2]=789
$echo
${array_1[99999999999999999999999999999999999999999999999999999999999999999999]}
It actually returned 789!
Looks like integer overflow to me. Array indices are 64-bit integers,
and you've exceeded that range.

imadev:~$ unset a
imadev:~$ a[2]=789
imadev:~$ echo "${a[2]} ${a[18446744073709551618]}"
789 789

You just got really (un)lucky with your string of 9s happening to map
back to 2, modulo 2^64.
dualbus
2017-06-02 13:56:29 UTC
Permalink
On Fri, Jun 02, 2017 at 09:49:09AM -0400, Greg Wooledge wrote:
[...]
Post by Zhiyuan Gao
It actually returned 789!
Looks like integer overflow to me. Array indices are 64-bit integers,
and you've exceeded that range.
From the bash manual:

ARITHMETIC EVALUATION

The shell allows arithmetic expressions to be evaluated, under
certain circumstances (see the let and declare builtin commands, the
(( compound command, and Arithmetic Expansion). Evaluation is done
in fixed-width integers with no check for overflow, though division
by 0 is trapped and flagged as an error. The operators and their
precedence, associativity, and values are the same as in the C
language. The following list of operators is grouped into levels of
equal-precedence operators. The levels are listed in order of
decreasing precedence.

So you have to ensure your indices don't overflow.
--
Eduardo Bustamante
https://dualbus.me/
Loading...