PHP memory_get_peak_usage and ini_set(‘memory_limit’, ‘-1’)

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

My quesiton was:

I recently ran into memory allocation problems, so I started experimenting with the ini_set('memory_limit', value); directive where I tried to enter values incrementaly. Now, searching through the web (and SO) I found out that I can put -1 as the value. So, I did and now the script runs fully to the end without breaking (before I used to get the memory allocation error).

What I don’t understand, however, is that given these two lines at the end of the script’s file:

$mem = memory_get_peak_usage(true);         
echo "Peak mem. usage: <b>". round($mem /1024/10124,2)."</b> MB";

produce around 10.8MB and when I look into the /var/log/messages I can see this line:

Nov2113:52:26 mail suhosin[1153]: ALERT-SIMULATION - script tried to increase  
memory_limit to 4294967295 bytes which is above the allowed value (attacker  
'xx.xxx.xxx.xxx', file '/var/www/html/file.php', line 5)

which means the script tried to alocate 4096MB!

How can this be? And also, what interest me the most is why didn’t the script execution stop in this case? Is it because of the ini_set('memory_limit', '-1');? I mean, I did read that putting -1 as the valueis not recomended and I know where the problem lies in the script (reading too big amount of data at once in the memory), and I will go and fix it with sequential reading, but I’m just baffled about these data differences, so I would be gratefull if someone can shed some light on it.

The answer, by user Sverri M. Olsen was:

It is because the suhosin patch uses its own “hard” maximum memory limit, suhosin.memory_limit.

From the configuration reference:

Suhosin […] disallows setting the memory_limit to a value greater than the one the script started with, when this option is left at 0.

In other words, if you change the memory_limit so that it is bigger than suhosin’s upper limit then it will simply assume that you are an “attacker” trying to do something suspicious

Written by Nikola Brežnjak