Why does PHP strlen () return a negative length?

strlen($str) returns negative values ​​for the "huge string" that is created with str_repeat :

 <?php error_reporting(E_STRICT|E_ALL); echo phpversion(); // 5.3.26 echo PHP_INT_MAX; // 9223372036854775807 ini_set('memory_limit', '-1'); ini_set('max_execution_time', 0); $gb = 1024 * 1024 * 1024; $str = str_repeat('a', 2 * $gb); echo strlen($str); // gives int(-2147483648) echo $str[0]; // Notice: Uninitialized string offset: 0 $str2 = str_repeat('a', 4 * $gb); echo strlen($str2); // gives int(0) $str3 = str_repeat('a', 123 + 4 * $gb); echo strlen($str3); // gives int(123) $str4 = str_repeat('a', 6 * $gb); // starts to wrap again... echo strlen($str4); // gives int(-2147483648) echo $str4[0]; // Notice: Uninitialized string offset: 0 $str5 = str_repeat('a', 123 + 8 * $gb); echo strlen($str5); // gives int(123) ?> 

Is this behavior defined?

Or is this a PHP bug?

+12
string debugging php
Jul 10 '13 at 16:23
source share
2 answers

string can reach 2 GB.

It looks like it really is (2GB - 1). This works fine on my x64 field:

 $str = str_repeat('a', 2 * 1024 * 1024 * 1024 -1); echo $str[0]; 

... while this is interrupted:

 $str = str_repeat('a', 2 * 1024 * 1024 * 1024); echo $str[0]; 

What you do is simply undefined and the manual should be fixed. I would also expect a warning.

Interestingly, this leads to a fatal error:

 $str = str_repeat('a', 2 * 1024 * 1024 * 1024 -2); // 2GB - 2 bytes $str .= 'b'; // ok $str .= 'c'; // PHP Fatal error: String size overflow 




Update:

The report reports an error . The documentation on php.net has been fixed and now it says "maximum 2147483647 bytes."

+5
Jul 10 '13 at 16:59
source share

I assume you are just overflowing int with your big string. From the manual:

The size of the integer depends on the platform, although the maximum value of about two billion is the usual value (this is 32 bits). PHP does not support unsigned integers. Integer size can be determined using the constant PHP_INT_SIZE and the maximum value using the constant PHP_INT_MAX with PHP 4.4.0 and PHP 5.0.5.

So this should be OK if your row size can fit in int.

+2
Jul 10 '13 at 16:29
source share



All Articles