Jump to content

Simple for() exhausting memory


Mahngiel

Recommended Posts

// in this case, $teams_count = 16
for($j = $tournament->teams_count; $j != 1; $j/2)
{
echo $j;
}

 

What I expect:

16 | 8 | 4 | 2 | 1

 

What I get: memory exhaustion.

PHP Fatal error:  Allowed memory size of 134217728 bytes exhausted (tried to allocate 128716801 bytes)

 

Is it so late, I'm missing something?

Link to comment
https://forums.phpfreaks.com/topic/258807-simple-for-exhausting-memory/
Share on other sites

If you are interested, I solved my own problem by ditching a for() and adding a while()

while($tournament->team_count >= 1)
{
	for($j = 1; $tournament->team_count >= 1;$j++)
	{
		echo '<div id="round_' . $j . '">'; 

		for($i = 1; $i <= $tournament->team_count; $i++)
		{
			echo '<div class="tourney_cell">Player ' . $i . '</div>';
		}

		echo '</div>';

		$tournament->team_count = $tournament->team_count / 2;
	}
}

That while loop is redundant. It's not the while loop that fixed it, it's the change of $!= to >=

 

Actually, not wholly correct.  The while loop was redundant, but the issue lies in expression 3 and the fact that i never changed the stored value of $j.

 

// original loop
for($j = $tournament->teams_count; $j != 1; $j/2)

// fixed loop
for($j = $tournament->teams_count; $j != 1; $j= $j/2)

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.