How to prevent buffer overflows?
Posted: Sat May 03, 2008 2:33 pm
I am having some problem where if I fill a variable with too much stuff, the program halts without providing any reason.
What I would like to know is how to prevent buffer overflows before they occur.
How my problem occurs is when I am reading in a large amount of data from a file. The file is read line by line using fgets() (line 1), and each line is appended to the current data within a buffer variable (line 2):
Somewhere when $buffer is filled with 10M and 30M bytes, appending a new line of data after many others (at line 2) overflows the buffer and the program exits without warning or reason.
I have tried capturing the error by wrapping the code with an exception handler, and even set error handler function with error level set to E_ALL, but to no avail can I determine for sure this is a buffer overload error.
Assuming it is a buffer overload error, is there any way to prevent this problem in the future?
Jeff in Seattle
What I would like to know is how to prevent buffer overflows before they occur.
How my problem occurs is when I am reading in a large amount of data from a file. The file is read line by line using fgets() (line 1), and each line is appended to the current data within a buffer variable (line 2):
Code: Select all
$line_buffer = fgets($fh, 4096);
$buffer .= $line_buffer;I have tried capturing the error by wrapping the code with an exception handler, and even set error handler function with error level set to E_ALL, but to no avail can I determine for sure this is a buffer overload error.
Assuming it is a buffer overload error, is there any way to prevent this problem in the future?
- Is there a way to pre-determine the maximum allowable size a buffer can be before it overflows (and thus causing the program to crash)?
- Is there a way to pre-declare the desired size of a buffer to prevent it from having an overflow situation?
- Does PHP have the concept of memory-mapping a buffer variable to a file, thereby be able to handle large amounts of data?
Jeff in Seattle