I am having a problem understanding why this part of my code is causing a memory leak:
for($i=0; $i<count($values); $i++){
$values[$i] = addslashes($values[$i]);
}
To put the code in context, i have a previously built array called values, which has all the values to be inserted into a database. all the fields are strings so i need to escape all of them and for this application addslashes or mysql_real_escape_string are a good choice imo.
Now the strange thing is that as soon as i added the part shown above, i get a message like this:
PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 24 bytes)
I understood that this generated a memory leak but i don’t know why.
Digging in, i commented out the only line in the for loop, leaving the for statement just for curiosity, and the leak is gone. Any ideas what could this possibly mean?
PS: The strings are all UTF8 encoded, could that be a problem?
EDIT:
The array contains something like this :
Array (
[dossier] => 002A
[permis] =>
[adresse] => 18, rue Bellevue
[ville] => Ste-Anne-des-Lacs (Québec)
[province] =>
[code_postal] => J0R 1B0
[numero_centrale] => N/A
[routes] => De la Gare, droite chemin Avila jusqu'au bout et droite chemin Ste-Anne-des-lacs sur 1,8 km et droite sur Bellevue.
)
Your array has string keys, but you are checking/assigning numeric keys. As @nickb notes, each time you add a numeric key,
count($values)increases by one, so you have an infinite loop. Hence the memory exhaustion.Check with a debugger, or better yet, switch to a
foreachloop or one of thearray_*functions (array_walk(),array_map(), etc. depending on what you are trying to do).@Jeremy correctly points out that you should not be using
addslashes()to escape your strings. Look atmysqli_real_escape_string()(as he suggests), or better yet, consider usingPDOif you can.