The Fatal Error
Recently I encountered a specific error with one of my PHP applications. Like any other programmer, I thought of googling the issue.
After some research, I found that for some reason my script was taking all the memory space. As I was on shared hosting and ini_set was disabled by the server admin, I had no other option than finding the root cause of the issue.
The Incorrect Solution: Increasing Memory
Solutions such as simply increasing the memory limit (e.g., in php.ini) are often not the correct solution. By doing that, you are merely allowing your bad script to consume all the memory.
The Root Cause: Data Reassignment
So how do we solve the issue? First, we must look at how variables handle data in loops.
Suppose you are creating a variable that is carrying a large amount of data. In a loop, you are reassigning a value to that variable.
When you reassign too much data to the same variable, even though its values are getting updated, the memory is not getting freed yet because the variable is technically "in use" and the Garbage Collector is not clearing that memory immediately.
The Correct Solution: Garbage Collection
To avoid the "Allowed memory size exhausted" error, you can set the value to null.
By doing so, you are telling the Garbage Collector that whatever data was kept in memory for that variable is no longer required and can be freed. The Garbage collector will immediately clear the space.
- Identify the variable consuming large amounts of data.
- After the data is used, explicitly set the variable to
null. - This triggers the cleanup process immediately, freeing up RAM for the rest of the script.