PHP: Memory leak in implicit __toString() call with certain functions

November 30th, 2007

See the gory details in http://bugs.php.net/bug.php?id=43450.

Basically, there are function which expect strings and the implicit _toString() call on an object will leak memory. Testcase:

< ?php
    class Foo {
        function __toString() {
            return 'foo';
        }
    }
    for ($i = 0; $i < 1e5; $i++) {

        $o = new Foo;

        # leaks
        md5($o);
        # does not leak
        #md5($o->__toString());

        # does not leak either way
        # strstr($o, 'f');
        #strstr($o->__toString(), 'f');

        if ($i % 1e3 == 0) {
            printf("%u: %1.2f KB\n",
                $i, memory_get_usage(true) / 1024);
        }
    }

Entry Filed under: PHP

Leave a Comment

hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed


Calendar

November 2007
M T W T F S S
« Aug   Jan »
 1234
567891011
12131415161718
19202122232425
2627282930  

Most Recent Posts