Page 1 of 1

How to prevent buffer overflows?

Posted: Sat May 03, 2008 2:33 pm
by jefftanner
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):

Code: Select all

$line_buffer = fgets($fh, 4096);
$buffer .= $line_buffer;
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?
  • 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?
Thanks

Jeff in Seattle

Re: How to prevent buffer overflows?

Posted: Sun May 04, 2008 12:13 am
by yacahuma
check your php.ini file. There you will find limit to the memory php uses. You can play with that depending on what you are doing.

In anycase is not a good idea to use the memory as it was unlimited. If you required this kind of stuff , consider using the hard drive.

Re: How to prevent buffer overflows?

Posted: Sun May 04, 2008 10:18 am
by jefftanner
Within my /etc/php5/cli/php.ini file: memory_limit = 128M

The overflow occurs way before this limit.

In other programming languages, one could reserve a fixed amount of memory space for a buffer variable to assure that overflow would not occur. Is this not possible in PHP?

Thanks

Jeff in Seattle

Re: How to prevent buffer overflows?

Posted: Sun May 04, 2008 10:34 am
by printf
Use...

Code: Select all

strace -e trace=3Dfile php script.php

Re: How to prevent buffer overflows?

Posted: Thu May 08, 2008 12:13 pm
by jefftanner
To last responder printf

I am sorry, but I do not understand your reply that I should use the LENUX command strace which is used to trace system calls and signals.

I am looking for is a way to either pre-determine or pre-assign the maximum buffer size for a $variable.

Thanks