#29950 [Opn]: Nondeterministic behavior of array inner pointer
| From: | tomas_matousek at hotmail dot com | Date: | Sat, 04 Sep 2004 07:07:48 +0000 |
| Subject: | #29950 [Opn]: Nondeterministic behavior of array inner pointer | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-65710@lists.php.net to get a copy of this message | ||
ID: 29950
User updated by: tomas_matousek at hotmail dot com
Reported By: tomas_matousek at hotmail dot com
Status: Open
Bug Type: Arrays related
Operating System: all
PHP Version: 5.0.1
New Comment:
Of course, there is copy-on-write.
That's a reason why reseting array inner pointer on copy is a bug.
Previous Comments:
------------------------------------------------------------------------
[2004-09-03 11:08:53] andrey@php.net
http://www.zend.com/zend/art/ref-count.php
------------------------------------------------------------------------
[2004-09-03 10:53:26] andrey@php.net
I think it is mentioned in the manual that PHP uses copy-on-write
technique. This means that if
$a = array(1,2,3);
and
$b = $a;
there is _only_ 1 array and $b reference this array. When change has
been made the copy-on-write starts to work. AFAIK it is not only for
arrays...
Simple example :
php -r '$a=str_repeat("a", 10000000);while ($i++<2000) ${"a".$i} = $a;
This thing creates a very long string ~ 10MB, and then reference it
2000 times. If there was no copy-on-write then I will need 2*10^10
memory, which is more than a process on 32bit architecture can
address.
------------------------------------------------------------------------
[2004-09-02 14:22:19] tomas_matousek at hotmail dot com
Description:
------------
In the manual page describing each() function is the following
caution:
"Because assigning an array to another variable resets the original
arrays pointer, ..."
I think that this is a bug, although it is documented and treated as
feature.
I realized that the pointer is reset when a copy of an array is made.
However, PHP makes some optimizations which prevents unnecessary array
copying (which is good feature).
Since these optimizations are not known for users (and shouldn't be)
the behavior of inner pointer is thus non-deterministic from user's
point of view.
See the follwoing code.
Its output depends on whether the statement $b[] = 1; is commented or
not.
Reproduce code:
---------------
function f($a) { $b = $a; /*$b[] = 1;*/ return $b; }
$arrayOuter = array("key1","key2");
$arrayInner = array("0","1");
while(list(,$o) = each($arrayOuter))
{
$q = f($arrayInner);
while(list(,$i) = each($arrayInner))
{
print "inloop $i for $o\n";
}
}
Expected result:
----------------
inloop 0 for key1
inloop 1 for key1
Actual result:
--------------
inloop 0 for key1
inloop 1 for key1
inloop 0 for key2
inloop 1 for key2
------------------------------------------------------------------------
--
Edit this bug report at http://bugs.php.net/?id=29950&edit=1